在 JavaScript 中通过 id 属性搜索复杂对象
假设我们有一个类似这样的复杂 JSON 对象 −
const obj = {
"id": "0001",
"fieldName": "sample1",
"fieldValue" "0001",
"subList": [
{
"id": 1001,
"fieldName": "Sample Child 1",
"fieldValue": "1001",
"subList": []
},
{
"id": 1002,
"fieldName": "Sample Child 2",
"fieldValue": "1002",
"subList": []
}
]
}我们需要编写一个 JavaScript 函数,该函数接受这样的一个对象和一个 key 值对(必须是 "id" key-value 对)。然后该函数应返回包含所查询 key/value 对的整个子对象。
示例
代码如下 −
const obj = {
"id": "0001",
"fieldName": "sample1",
"fieldValue": "0001",
"subList": [
{
"id": 1001,
"fieldName": "Sample Child 1",
"fieldValue": "1001",
"subList": []
},
{
"id": 1002,
"fieldName": "Sample Child 2",
"fieldValue": "1002",
"subList": []
}
]
}
function searchById(searchKey, obj) {
let key = Object.keys(searchKey)[0];
let res;
if (obj[key] === searchKey[key]) {
return obj;
};
obj.subList.some(function (a) {
res = searchById(searchKey, a);
return res;
});
return res;
}
console.log(searchById({id: 1002}, obj));输出
控制台输出如下 −
{
id: 1002,
fieldName: 'Sample Child 2',
fieldValue: '1002',
subList: []
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP