如何从嵌套的json对象中获取匹配的子对象
我有这样一个obj:如何从嵌套的json对象中获取匹配的子对象,json,nested,javascript-objects,Json,Nested,Javascript Objects,我有这样一个obj: var obj = { thing1 : { name: 'test', value: 'testvalue1'}, thing2 : { name: 'something', thing4: {name:'test', value: 'testvalue2'}}, } 我想编写一个类似findByName(obj,'test')的函数。它返回具有相同名称的所有匹配子对象。因此,它应该返回: {name:'test',value
var obj = { thing1 : { name: 'test', value: 'testvalue1'},
thing2 : { name: 'something', thing4: {name:'test', value: 'testvalue2'}},
}
我想编写一个类似findByName(obj,'test')的函数。它返回具有相同名称的所有匹配子对象。因此,它应该返回:
{name:'test',value:'testvalue1'}
{名称:'test',值:'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;
}
显然,它只返回第一个匹配项。。如何改进这种方法 您需要将结果推送到一个数组中,并使函数返回一个数组 此外,还要检查对象是否为null或未定义,以避免出现错误。 这是你的代码修改。 注意:我还修改了父对象“obj”,添加了一个值为“test”的“name”属性,因此结果中也应该包含父对象
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");
在控制台中运行此命令,如果有帮助,请向上投票