C.ayoub
C.ayoub

Reputation: 19

how to merge an array of objects to an array of objects contain object an array

is there a way to "merge" an array of objects' values?

For example, I would like to take an array like this . . .

input = [{name: 'x', data: 2},{name: 'y', data: 5},{name: 'x', data: 4},{name: 'y', data: 3}];

. . . and transform it into this

output = [{name: 'x', data: [2,4]},{name: 'y', data: [5,3]}]

Upvotes: 0

Views: 71

Answers (3)

sudo97
sudo97

Reputation: 914

You can accomplish this by generating a new array. Simply iterate through the input array and start accumulating the data values of every unique name field into the new merged array. The code would look something like this:

function merge(input){
    let merged = [];
    for (let i=0; i<input.length;i++) {
        let found = merged.findIndex(e => e.name === input[i].name);
        if (found === -1) {
             merged.push({ name: input[i].name, data: [ input[i].data ] });
        } else {
             merged[found].data.push(input[i].data);
        }
    }
    return merged;
}

Upvotes: -1

Ben Wainwright
Ben Wainwright

Reputation: 4651

Here's my solution:

const output = input.reduce((previous, next, currentIndex, array) => {
  const index = previous.findIndex((item) => item.name === next.name);
  if (index >= 0) {
    previous[index].data.push(next.data);
  } else {
    previous.push({ ...next, data: [next.data] });
  }
  return previous;
}, []);

Upvotes: 2

INspace
INspace

Reputation: 89

Try this:

    let input = [{name: 'x', data: 2},{name: 'y', data: 5},{name: 'x', data: 4},{name: 'y', data: 3}];
    let out = [...new Set(input.map(i => i.name))].map(i => {
        return {name: i, data: input.filter(j => j.name === i).reduce((a,b)=> [a.data].concat([b.data])) };
    });
    console.log(out);

Upvotes: 2

Related Questions