1
array = [
  {name:'alfa', firstValue:{value:'100'}},
  {name:'alfa', secoundValue:{value:'200'}},
  {name:'alfa', thirdValue:{value:'300'}}
]

I'm looking for a way to copy objects props into unique when the value name are the same, how can I do this, see expected result below:

array = [
  {name:'alfa', firstValue:{value:'100'}, secoundValue:{value:'200'}, thirdValue:{value:'300'}},
]
0

1 Answer 1

1

You can use Array.reduce and Object.assign:

array = [
  {name:'alfa', firstValue:{value:'100'}},
  {name:'alfa', secoundValue:{value:'200'}},
  {name:'alfa', thirdValue:{value:'300'}}
]

const result = array.reduce((a, b) => {
  let found = a.find(e => e.name == b.name);
  found ? Object.assign(found, b) : a.push(b);
  return a;
}, [])

console.log(result);

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

2 Comments

Thanks I was looking for exactly reducer + object assign, works great!
The main downside here is O(n^2) performance; besides that it's a fine solution

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.