Reputation: 531
I have the following JSON format which is dynamic i.e., number of children can be different at anytime.
var Obj = {
"name": "A",
"count": 13,
"children": [{
"name": "B",
"count": 24,
"children": [{
"name": "C",
"count": 35,
"children": [],
"msg": null
},{
"name": "D",
"count": 35,
"children": [],
"msg": "Err"
}]
}]
}
How can we find if msg is not null in entire object Obj? I tried to use loop through objects but this format is not consistent as children array in the object is dynamic.I am new to underscore, Is there anyway to check with Underscore JavaScript?
Upvotes: 0
Views: 1175
Reputation: 322
If I understood your question correctly...
var anyMsgNotNull = (_.filter(Obj.children, function(child) {
return (child.msg !== null);
})).length > 0;
This will return true if there are any msg elements that are not null, otherwise it will return false.
Upvotes: 1
Reputation: 901
Yes Underscore the library which can help out like this:-
_.each(Obj.children,function(item){ //it will take item one by one and do
// processing
if(item.msg){
//DO YO THING
}
return;
})
Upvotes: 0
Reputation: 122037
In plain js you can create recursive function using for...in
loop that will return false if property with key msg
and value null
is found otherwise it will return true
var Obj = {"name":"A","count":13,"children":[{"name":"B","count":24,"children":[{"name":"C","count":35,"children":[],"msg":null},{"name":"D","count":35,"children":[],"msg":"Err"}]}]}
function notNull(obj) {
var result = true;
for (var i in obj) {
if (i == 'msg' && obj[i] === null) result = false;
else if (typeof obj[i] == 'object') result = notNull(obj[i]);
if (result == false) break;
}
return result;
}
console.log(notNull(Obj))
Upvotes: 0