2017-04-11 3 views
0

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

msg가 전체 개체 Obj에서 null이 아닌지 어떻게 확인할 수 있습니까? 객체를 통해 루프를 사용하려고했으나 객체의 배열이 동적 인 경우이 형식이 일관되지 않습니다. 언더 스코어가 새로 생겼습니다. 언더 코어 JavaScript로 검사 할 곳이 있습니까? 일반 JS에서

+0

순수 js 솔루션을 원하거나 underscore.js 솔루션을 찾고 계십니까? –

+0

무엇이든 괜찮습니다 – user521024

+0

함수를 반환 하시겠습니까? 메시지가 null이거나 그와 비슷한 속성 인'name' 속성을 가진 일종의 객체 배열입니까? –

답변

0

당신이 키 msg과 가치 null와 속성이 그렇지 발견 된 경우 false를 반환합니다 for...in 루프를 사용하여 재귀 함수를 만들 수는 반환 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))

0

예 언더 스코어 이런 도움을 줄 수있는 도서관 : -

_.each(Obj.children,function(item){ //it will take item one by one and do 
            // processing 
    if(item.msg){ 
     //DO YO THING 
    } 
    return; 
}) 
1
내가 제대로 질문을 이해하면

...

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

null이되지 않은 MSG 요소가있는 경우는 true를 돌려줍니다, 그렇지 않으면 false를 반환합니다.