在 JavaScript 中通过 id 属性搜索复杂对象
javascriptweb developmentfront end technologyobject oriented programming
假设我们有一个像这样的复杂 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 函数,该函数接受一个这样的对象和一个键值对(必须是"id"键值对)。然后,该函数应返回包含查询的键/值对的整个子对象。
示例
其代码为 −
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: [] }