深度搜索JSON对象JavaScript
假设我们有以下嵌套的JSON对象-
const obj = {
id: 1,
title: 'hello world',
child: {
id: null,
title: 'foobar',
child: {
id: null,
title: 'i should be in results array '
}
},
foo: {
id: null,
title: 'i should be in results array too!' },
deep: [
{
id: null,
value: 'yo'
}, {
id: null,
value: 'yo2'
}
]
};我们需要编写一个JavaScript函数,该函数接受一个对象作为第一个参数,将键字符串作为第二个参数,将值字符串作为第三个参数。然后,该函数应在JSON对象中检查给定的键值对。
如果存在任何对象,则该函数应返回所有此类对象的数组。
我们将使用以下方法来解决此问题-
如果搜索到的项目为false或不是对象,则返回
如果给定的键和值匹配,则将实际对象添加到结果集中,
我们获得键并遍历属性,然后再次调用该函数。
最后,我们返回包含所收集对象的数组。
示例
const obj = {
id: 1,
title: 'hello world',
child: {
id: null,
title: 'foobar',
child: {
id: null,
title: 'i should be in results array '
}
},
foo: {
id: null,
title: 'i should be in results array too!' },
deep: [
{
id: null, value: 'yo'
}, {
id: null, value: 'yo2'
}
]
};
const findObject = (obj = {}, key, value) => {
const result = [];
const recursiveSearch = (obj = {}) => {
if (!obj || typeof obj !== 'object') { return;
};
if (obj[key] === value){
result.push(obj);
};
Object.keys(obj).forEach(function (k) {
recursiveSearch(obj[k]);
});
} recursiveSearch(obj);
return result;
} console.log(findObject(obj, 'id', null));输出结果
[
{
id: null,
title: 'foobar',
child: {
id: null, title: 'i should be in results array '
}
},
{
id: null, title: 'i should be in results array '
}, {
id: null, title: 'i should be in results array too!'
}, {
id: null, value: 'yo'
}, { id: null, value: 'yo2'
}
]热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短