Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ค้นหาในอ็อบเจ็กต์ซับซ้อนด้วย property id - JavaScript

JSON object ซ้อนมี property id และ subList ค้นหา node ที่ 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: []
}

คำอธิบาย: Recursive function ตรวจสอบ node ปัจจุบัน ถ้า id ตรง คืน node มิฉะนั้น some() วนลูกใน subList เรียก recursive some หยุดเมื่อ callback คืน truthy (found)