ในการแบนอาร์เรย์ JavaScript ของออบเจ็กต์ลงในอ็อบเจ็กต์ เราได้สร้างฟังก์ชันที่รับอาร์เรย์ของอ็อบเจ็กต์เป็นอาร์กิวเมนต์เพียงอย่างเดียว ส่งคืนวัตถุที่แบนพร้อมคีย์ต่อท้ายดัชนี ความซับซ้อนของเวลาคือ O(mn) โดยที่ n คือขนาดของอาร์เรย์ และ m คือจำนวนคุณสมบัติในแต่ละอ็อบเจ็กต์ อย่างไรก็ตาม ความซับซ้อนของช่องว่างคือ O(n) โดยที่ n คือขนาดของอาร์เรย์จริง
ตัวอย่าง
//code to flatten array of objects into an object
//example array of objects
const notes = [{
title: 'Hello world',
id: 1
}, {
title: 'Grab a coffee',
id: 2
}, {
title: 'Start coding',
id: 3
}, {
title: 'Have lunch',
id: 4
}, {
title: 'Have dinner',
id: 5
}, {
title: 'Go to bed',
id: 6
}, ];
const returnFlattenObject = (arr) => {
const flatObject = {};
for(let i=0; i<arr.length; i++){
for(const property in arr[i]){
flatObject[`${property}_${i}`] = arr[i][property];
}
};
return flatObject;
}
console.log(returnFlattenObject(notes)); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์ในคอนโซล -
[object Object] {
id_0: 1,
id_1: 2,
id_2: 3,
id_3: 4,
id_4: 5,
id_5: 6,
title_0: "Hello world",
title_1: "Grab a coffee",
title_2: "Start coding",
title_3: "Have lunch",
title_4: "Have dinner",
title_5: "Go to bed"
}