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

รวมออบเจกต์ในอาร์เรย์ตามคีย์ที่คล้ายกันใน JavaScript


สมมติว่าเรามีอาร์เรย์ของออบเจกต์ดังนี้

const arr = [    {id: 1, h1: 'Daily tests'},    {id: 2, h1: 'Details'},    {id: 1, h2: 'Daily classes'},    {id: 3, h2: 'Results'},    {id: 2, h3: 'Admissions'},    {id: 1, h4: 'Students'},    {id: 2, h5: 'Alumni'},    {id: 3, h3: 'Appreciations'},    {id: 1, h5: 'Tiny Tots'},    {id: 1, h6: 'Extras'}, ];

เราต้องเขียนฟังก์ชันที่แปลงอาร์เรย์นี้เป็นอาร์เรย์ที่หัวข้อทั้งหมด (h1, h2, h3 ...) ที่มี id เดียวกันถูกรวมอยู่ในออบเจกต์เดียวกัน ดังนั้นมาเขียนโค้ดสำหรับฟังก์ชันนี้

ตัวอย่าง

const arr = [    {id: 1, h1: 'Daily tests'},    {id: 2, h1: 'Details'},    {id: 1, h2: 'Daily classes'},    {id: 3, h2: 'Results'},    {id: 2, h3: 'Admissions'},    {id: 1, h4: 'Students'},    {id: 2, h5: 'Alumni'},    {id: 3, h3: 'Appreciations'},    {id: 1, h5: 'Tiny Tots'},    {id: 1, h6: 'Extras'}, ]; const clubArray = (arr) => {    return arr.reduce((acc, val, ind) => {       const index = acc.findIndex(el => el.id === val.id);       if(index !== -1){          const key = Object.keys(val)[1];          acc[index][key] = val[key];       } else {          acc.push(val);       };       return acc;    }, []); }; console.log(clubArray(arr));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้

[    {       id: 1,       h1: 'Daily tests',       h2: 'Daily classes',       h4: 'Students',       h5: 'Tiny Tots',       h6: 'Extras'    },    { id: 2, h1: 'Details', h3: 'Admissions', h5: 'Alumni' },    { id: 3, h2: 'Results', h3: 'Appreciations' } ]