深度搜索 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 对象中检查给定的键值对。
如果有任何对象,则函数应返回所有此类对象的数组。
我们将使用以下方法来解决此问题 −
- 如果搜索的项目为假或不是对象,那么我们返回
- 如果给定的键和值匹配,那么我们向结果集添加实际对象,
- 我们获得键并迭代遍历属性并再次调用函数。
最后,我们返回包含已收集到的对象的数组。
示例
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'
}
]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP