สมมติว่าเรามี JSON Object ที่ซับซ้อนเช่นนี้ -
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: []
}