0

I am trying to merge objects of an array into one if they have the same key.

Having this array:

let data = [
  { id: "1", cars: 5 }, 
  { id: "1", pasta: 2 },
  { id: "2", cars: 0 }, 
  { id: "2", pasta: 0 },
];

I would like to achieve this:

let data = [
  { id: "1", cars: 5, pasta: 2 },
  { id: "2", cars: 0, pasta: 0 },
];

I am looking for any solutions, but preferable ES6.

2 Answers 2

1

Here's a solution that combines the Array reduce method and the Object values method. One benefit of this approach is that it is O(n) time complexity, which would only really matter if you had a ton of data, but still potentially more efficient than the solutions that include loops inside loops.

let data = [
  { id: "1", cars: 5 }, 
  { id: "1", pasta: 2 },
  { id: "2", cars: 0 }, 
  { id: "2", pasta: 0 },
];

const combined = Object.values(data.reduce((acc, el) => {
  acc[el.id] = { ...acc[el.id], ...el };
  return acc;
}, {}));

console.log(combined);

Sign up to request clarification or add additional context in comments.

Comments

0

Using Array.prototype.reduce():

let data = [
  { id: "1", cars: 5 }, 
  { id: "1", pasta: 2 },
  { id: "2", cars: 0 }, 
  { id: "2", pasta: 0 },
]

const result = data.reduce((items, item) => {
  const existingItem = items.find(({ id }) => id === item.id)

  if (existingItem) Object.assign(existingItem, item)
  else items.push({ ...item })

  return items
}, [])

console.log(result)

// Original array is left intact:
console.log(data)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.