比较两个对象时对数组嵌套值进行分组 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming
假设我们有以下 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 及其特征分组到一行中。
并且所需的输出可以通过以下视觉表示更好地描述。
我们需要编写一个以相同方式对数据进行分组和排序的函数。
示例
以下是代码 −
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' } ] ]