Adharsh Chottu
Adharsh Chottu

Reputation: 145

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 => (p.x === o.x) && (p.y === o.y) );
    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" }
];

Upvotes: 0

Views: 1877

Answers (3)

GMKHussain
GMKHussain

Reputation: 4661

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[d.x] ??= {x: d.x, y: d.y };
  acc[d.x].stroke = d.stroke;
  acc[d.x].color = d.color;
 
  return acc;
}, {});

console.log(Object.values(result));

Upvotes: 0

Amila Senadheera
Amila Senadheera

Reputation: 13215

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);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386522

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 => [o.x, o.y].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; }

Upvotes: 1

Related Questions