深度搜索 JSON 对象 JavaScript
javascriptweb developmentfront end technologyobject oriented programmingjson
假设我们有以下嵌套 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'
}
]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

