สมมติว่าเรามีวัตถุ JSON ต่อไปนี้ -
const input = { "before": { "device": [ { "id": "1234", "price": "10", "features": [ { "name": "samsung", "price": "10" }, { "name": "Apple", "price": "20" } ] }, { "id": "2154", "price": "20", "features": [ { "name": "samsung", "price": "30" }, { "name": "Moto", "price": "40" } ] } ] }, "after": { "device": [ { "id": "1234", "price": "50", "features": [ { "name": "samsung", "price": "20" }, { "name": "Lenovo", "price": "30" } ] }, { "id": "2158", "price": "40", "features": [ { "name": "samsung", "price": "30" } ] } ] } };
ข้อกำหนดของเราคือการจัดกลุ่ม id และคุณลักษณะเป็นแถวเดียว หากมี id เดียวกันในออบเจ็กต์ before &after
และผลลัพธ์ที่ต้องการสามารถอธิบายได้ดีขึ้นด้วยการแสดงภาพต่อไปนี้
เราจำเป็นต้องเขียนฟังก์ชันที่จัดกลุ่มและจัดเรียงข้อมูลในลักษณะเดียวกัน
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const input = { "before": { "device": [ { "id": "1234", "price": "10", "features": [ { "name": "samsung", "price": "10" }, { "name": "Apple", "price": "20" } ] }, { "id": "2154", "price": "20", "features": [ { "name": "samsung", "price": "30" }, { "name": "Moto", "price": "40" } ] } ] }, "after": { "device": [ { "id": "1234", "price": "50", "features": [ { "name": "samsung", "price": "20" }, { "name": "Lenovo", "price": "30" } ] }, { "id": "2158", "price": "40", "features": [ { "name": "samsung", "price": "30" } ] } ] } }; const formatJSON = data => { const sub = Object.fromEntries(Object.keys(data).map(k => [k, 0])); return Object.values(Object.entries(data).reduce((r, [col, { device }]) => { device.forEach(({ id, price, features }) => { r[id] = r[id] || [{ id, ...sub }]; r[id][0][col] = price; features.forEach(({ name, price }) => { let temp = r[id].find(q => q.name === name); if (!temp){ r[id].push(temp = { name, ...sub }); }; temp[col] = price; }); }); return r; }, {})); }; console.log(formatJSON(input));
ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้บนคอนโซล -
[ [ { id: '1234', before: '10', after: '50' }, { name: 'samsung', before: '10', after: '20' }, { name: 'Apple', before: '20', after: 0 }, { name: 'Lenovo', before: 0, after: '30' } ], [ { id: '2154', before: '20', after: 0 }, { name: 'samsung', before: '30', after: 0 }, { name: 'Moto', before: '40', after: 0 } ], [ { id: '2158', before: 0, after: '40' }, { name: 'samsung', before: 0, after: '30' } ] ]