假设我们有一个像这样的复杂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: [] }