0

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?

4
  • Are you looking for pure js solution also or just underscore.js solution? Commented Apr 11, 2017 at 11:10
  • Anything is fine Commented Apr 11, 2017 at 11:27
  • What do you want your function to return? Is it some sort of array of objects that has property name where message is null or something like that? Commented Apr 13, 2017 at 4:15
  • Can you clarify: you want to determine if there are literally any instances of a child having a non-null msg? Or do you want to know if ALL of the msg are non-null? Commented Apr 13, 2017 at 17:47

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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))

Comments

0

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;
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.