สมมติว่าเรามีวัตถุ JSON ที่ซ้อนกันเช่นนี้ -
const obj = {
"prop": [
{
"key": "FOO",
"value": "Foo is wonderfull, foo is great"
},
{
"key": "BAR",
"value": "Bar is bad, really bad"
}
]
}; เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับวัตถุเช่นอาร์กิวเมนต์แรก และสตริงคีย์เป็นอาร์กิวเมนต์ที่สอง
ฟังก์ชันของเราควรคืนค่าสำหรับคุณสมบัติ "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