Underscore JavaScript查找复杂Object中键的值

时间:2017-04-11 10:46:38

标签: javascript json for-loop underscore.js

我有以下JSON格式是动态的,即孩子的数量可以随时不同。

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"
        }]
    }]
}

如何在整个对象Obj中找到msg不为空?我尝试使用循环遍历对象,但这种格式不一致,因为对象中的子数组是动态的。我是下划线的新手,是否还要检查Underscore JavaScript?

3 个答案:

答案 0 :(得分:1)

如果我理解你的问题......

var anyMsgNotNull = (_.filter(Obj.children, function(child) {
    return (child.msg !== null);
  })).length > 0;

如果有任何msg元素不为null,则返回true,否则返回false。

答案 1 :(得分:0)

在普通的js中你可以使用for...in循环创建递归函数,如果找到带有键msg和值null的属性,它将返回false,否则它将返回true < / p>

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

答案 2 :(得分:0)

是Underscore图书馆可以提供这样的帮助: -

_.each(Obj.children,function(item){ //it will take item one by one and do 
                                    //  processing
  if(item.msg){
      //DO YO THING
   }
   return;
})