สมมติว่าเรามีอาร์เรย์ JSON ที่มีออบเจ็กต์คู่คีย์/ค่าเช่นนี้ -
const arr = [{
"key": "name",
"value": "john"
},
{
"key": "number",
"value": "1234"
},
{
"key": "price",
"value": [{
"item": [{
"item": [{
"key": "quantity",
"value": "20"
},
{
"key": "price",
"value": "200"
}]
}]
}]
}]; เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าว
ฟังก์ชันควรเตรียมอาร์เรย์ใหม่ที่มีการแสดงข้อมูลเทียบกับค่าคีย์แทนโครงสร้างที่ซับซ้อนนี้
ดังนั้นสำหรับอาร์เรย์ข้างต้น เอาต์พุตควรมีลักษณะดังนี้ −
const output = {
"name": "john",
"number": "1234",
"price": {
"quantity": "20",
"price": "200"
}
}; ตัวอย่าง
รหัสสำหรับสิ่งนี้จะเป็น −
const arr = [{
"key": "name",
"value": "john"
},
{
"key": "number",
"value": "1234"
},
{
"key": "price",
"value": [{
"item": [{
"item": [{
"key": "quantity",
"value": "20"
},
{
"key": "price",
"value": "200"
}]
}]
}]
}];
const simplify = (arr = []) => {
const res = {};
const recursiveEmbed = function(el){
if ('item' in el) {
el.item.forEach(recursiveEmbed, this);
return;
};
if (Array.isArray(el.value)) {
this[el.key] = {};
el.value.forEach(recursiveEmbed, this[el.key]);
return;
};
this[el.key] = el.value;
};
arr.forEach(recursiveEmbed, res);
return res;
};
console.log(simplify(arr)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
{
name: 'john',
number: '1234',
price: { quantity: '20', price: '200' }
}