ภาพรวม
สมมติว่าเรามี JSON object แบบซ้อน:
const obj = {
id: 1,
title: 'hello world',
child: {
id: null,
title: 'foobar',
child: {
id: null,
title: 'i should be in results array '
}
},
foo: {
id: null,
title: 'i should be in results array too!'
},
deep: [
{ id: null, value: 'yo' },
{ id: null, value: 'yo2' }
]
};
เราต้องเขียนฟังก์ชันที่รับอ็อบเจ็กต์, คีย์, และค่า แล้วค้นหาคู่คีย์-ค่านั้นในอ็อบเจ็กต์ คืนค่าอาร์เรย์ของอ็อบเจ็กต์ที่ตรงกันทั้งหมด
วิธีการ
- ถ้าอ็อบเจ็กต์เป็น falsy หรือไม่ใช่ object ให้ return
- ถ้าคีย์และค่าตรงกัน ให้เพิ่มอ็อบเจ็กต์นั้นเข้า result set
- ดึงคีย์ทั้งหมดและวนลูปเรียกฟังก์ชันซ้ำ
ตัวอย่างโค้ด
const obj = {
id: 1,
title: 'hello world',
child: {
id: null,
title: 'foobar',
child: {
id: null,
title: 'i should be in results array '
}
},
foo: {
id: null,
title: 'i should be in results array too!'
},
deep: [
{ id: null, value: 'yo' },
{ id: null, value: 'yo2' }
]
};
const findObject = (obj = {}, key, value) => {
const result = [];
const recursiveSearch = (obj = {}) => {
if (!obj || typeof obj !== 'object') {
return;
}
if (obj[key] === value) {
result.push(obj);
}
Object.keys(obj).forEach(function (k) {
recursiveSearch(obj[k]);
});
};
recursiveSearch(obj);
return result;
};
console.log(findObject(obj, 'id', null));
ผลลัพธ์
[
{ id: null, title: 'foobar', child: { id: null, title: 'i should be in results array ' } },
{ id: null, title: 'i should be in results array ' },
{ id: null, title: 'i should be in results array too!' },
{ id: null, value: 'yo' },
{ id: null, value: 'yo2' }
]