简体   繁体   中英

merge objects having same value as property in js

The data is an array, that has some objects in it. the objective here is to merge the objects which have same x and y values.

the code is given below:

 let data = [{ "x": 1, "y": 2, "color": "red" }, { "x": 1, "y": 2, "stroke": "violet" }, { "x": 3, "y": 4, "color": "green" }, { "x": 3, "y": 4, "stroke": "blue" }]; var finalArr = data.reduce((m, o) => { var found = m.find(p => (px === ox) && (py === oy) ); if (found) { found = {...o} } else { m.push(o); } return m; }, []);

the original data array is:

let data = [
{ "x": 1, "y": 2, "color": "red" },
{ "x": 1, "y": 2, "stroke": "violet" },
{ "x": 3, "y": 4, "color": "green" },
{ "x": 3, "y": 4, "stroke": "blue" }
];

the expected result is:

let data = [
{ "x": 1, "y": 2, "color": "red", "stroke": "violet" },
{ "x": 3, "y": 4, "color": "green", "stroke": "blue" }
];

You could use an object with a joined key and assign the actual object to the object for the group.

 const data = [{ x: 1, y: 2, color: "red" }, { x: 1, y: 2, stroke: "violet" }, { x: 3, y: 4, color: "green" }, { x: 3, y: 4, stroke: "blue" }], getKey = o => [ox, oy].join('|'), result = Object.values(data.reduce((r, o) => { Object.assign(r[getKey(o)]??= {}, o); return r; }, {})); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

First, accumulate key-value pairs for x and y key pair and finally and x and y as values into the same level.

This would also work.

 const data = [ { x: 1, y: 2, color: "red" }, { x: 1, y: 2, stroke: "violet" }, { x: 3, y: 4, color: "green" }, { x: 3, y: 4, stroke: "blue" }, ]; const output = Object.entries( data.reduce((prev, { x, y, ...rest }) => { if (prev[`${x}-${y}`]) { prev[`${x}-${y}`] = {...prev[`${x}-${y}`], ...rest }; } else { prev[`${x}-${y}`] = {...rest }; } return prev; }, {}) ).map(([key, value]) => { const [x, y] = key.split("-"); return { x, y, ...value }; }); console.log(output);

Simply do this

 let data = [{ "x": 1, "y": 2, "color": "red" }, { "x": 1, "y": 2, "stroke": "violet" }, { "x": 3, "y": 4, "color": "green" }, { "x": 3, "y": 4, "stroke": "blue" }]; let result = data.reduce((acc, d ) => { acc[dx]??= {x: dx, y: dy }; acc[dx].stroke = d.stroke; acc[dx].color = d.color; return acc; }, {}); console.log(Object.values(result));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM