สมมติว่าเรามีออบเจกต์ JSON แบบซ้อนกันดังนี้
const obj = {
"prop": [
{
"key": "FOO",
"value": "Foo is wonderfull, foo is great"
},
{
"key": "BAR",
"value": "Bar is bad, really bad"
}
]
};เราต้องเขียนฟังก์ชัน JavaScript ที่รับออบเจกต์ดังกล่าวเป็นอาร์กิวเมนต์แรก และสตริงคีย์เป็นอาร์กิวเมนต์ที่สอง
ฟังก์ชันควรคืนค่า property "value" ที่สอดคล้องกับคีย์ที่ระบุ
ตัวอย่างโค้ด
โค้ดสำหรับการทำงานนี้จะเป็นดังนี้
const obj = {
"prop": [
{
"key": "FOO",
"value": "Foo is wonderfull, foo is great"
},
{
"key": "BAR",
"value": "Bar is bad, really bad"
}
]
};
const findByKey = (obj, key) => {
const arr = obj['prop'];
if(arr.length){
const result = arr.filter(el => {
return el['key'] === key;
});
if(result && result.length){
return result[0].value;
}
else{
return '';
}
}
}
console.log(findByKey(obj, 'BAR'));ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
Bar is bad, really bad