Question:
Hello.
Let's say we have some object. We don't know its structure and what's inside, but we know that there should be, for example, an innerObject
object, which can be located anywhere inside. Here is an example object:
var someObj1 = {
io1: {sIo1:{ssIo01:'что-то'}}
oi2: {
sIo1:{
innerObject: {/*внутренности объекта*/}
}
}
}
And the structure of this object and where our innerObject
will be, we do not know. It is also known that innerObject
is NOT in an array.
How to find in some object, innerObject
object?
PS :
Without using any libraries.
Answer:
function checkInObject( obj, name ) {
var res = null;
for( var i in obj ) {
if(obj.hasOwnProperty(i)) {
if(i === name) {
res = obj[i];
break;
}
if(obj[i] && obj[i].constructor === Object) {
var check = checkInObject( obj[i], name );
if( check ) {
res = check;
break;
}
}
}
}
return res;
}
var someObj1 = {
io1: {sIo1:{ssIo01:'что-то'}},
oi2: {
sIo1:{
innerObject: { test : "done" }
}
}
}
console.log(checkInObject( someObj1, 'innerObject' ).test); // -> done