Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tìm kiếm đối tượng phức tạp theo thuộc tính id - JavaScript


Cho object lồng nhau có cấu trúc đệ quy (id, fieldName, fieldValue, subList). Viết hàm tìm và trả về sub-object chứa id khớp.

Ví dụ

Mã minh họa:

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));

Kết quả

Đầu ra:

{ id: 1002, fieldName: 'Sample Child 2', fieldValue: '1002', subList: [] }