Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ทำให้อาร์เรย์ออบเจ็กต์แบน (Flat) กลายเป็นออบเจ็กต์ใน JavaScript


เพื่อทำให้อาร์เรย์ออบเจ็กต์แบนกลายเป็นออบเจ็กต์ เราสร้างฟังก์ชันที่รับอาร์เรย์ออบเจ็กต์เป็นอาร์กิวเมนต์เดียว ฟังก์ชันจะคืนค่าออบเจ็กต์ที่แบนแล้ว โดย Key จะต่อด้วย Index ความซับซ้อนด้านเวลาคือ O(mn) โดย n คือขนาดอาร์เรย์ และ m คือจำนวนคุณสมบัติในแต่ละออบเจ็กต์ ส่วนความซับซ้อนด้านพื้นที่คือ O(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));

ผลลัพธ์

ผลลัพธ์ใน Console ดังนี้ −

[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" }