2015-10-22 69 views
0

子对象我有一个这样的OBJ:我应该如何获得匹配的嵌套JSON对象

var obj = { thing1 : { name: 'test', value: 'testvalue1'}, 
      thing2 : { name: 'something', thing4: {name:'test', value: 'testvalue2'}}, 
      } 

我想写像findByName函数(OBJ,“测试”),它返回所有匹配。具有相同名称的子对象。因此,它应该返回: {名称: '测试',值: 'testvalue1'} {名称: '测试',值: 'testvalue2'}

现在这是我所:

function findByName(obj, name) { 
    if(obj.name === name){ 
     return obj; 
    } 
    var result, p; 
    for (p in obj) { 
     if(obj.hasOwnProperty(p) && typeof obj[p] === 'object') { 
      result = findByName(obj[p], name); 
      if(result){ 
       return result; 
      } 
     } 
    } 

    return result; 
} 

显然它只返回第一个匹配。如何改进这个方法?

回答

0

您需要将结果推送到数组中并使该函数返回一个数组。

此外,请检查对象是否为空或未定义以避免错误。 这里是你的代码修改。 注意:我还通过添加一个名为“test”的“name”属性修改了父对象,即“obj”,所以结果中也应该包含父对象。在控制台

function findByName(obj, name) { 
    var result=[], p; 
    if(obj == null || obj == undefined) 
     return result; 
    if(obj.name === name){ 
     result.push(obj); 
    } 
    for (p in obj) { 
     if(obj.hasOwnProperty(p) && typeof obj[p] === 'object') { 
      newresult = findByName(obj[p], name); 
      if(newresult.length>0){ 

       //concatenate the result with previous results found; 
       result=result.concat(newresult); 
      } 
     } 
    } 

    return result; 
} 
var obj = { thing1 : { name: 'test', value: 'testvalue1'}, 
      thing2 : { name: 'something', thing4: {name:'test', value: 'testvalue2'}}, 
name:'test' //new property added 

      } 

//execute 
findByName(obj,"test"); 

运行这一点,并给予好评,如果这可以帮助你。