StevieB StevieB - 21 days ago 6
Javascript Question

JS/Es6 how to merge two arrays and override values in their objects

Lets say I have an array like this

let arrayOne = [{text="one", value=0},{text="two", value=0}]
let arrayTwo = [{text="two", value=5}]


So
arrayOne
will always the entire set of objects I want, but all the values will be 0.
arrayTwo
will have a subset of this array but will always have a value set. What I want is as follows, if
arrayTwo
objects exists in
arrayOne
then copy the value to the
arrayOne
object.

So in the end I would want

let arrayOne = [{text="one", value=0},{text="two", value=5}]


I did something like this, but I feel I am missing some es6 magic.

for (let orig of arrayOne) {
arrayTwo.find(item => {
if (item.value == orig.value) {
Object.assign(orig, item);
}
})
}

Answer

It is

arrayOne = arrayOne.map(item1 => {
  return Object.assign(item1, arrayTwo.find(item2 => {
    return item2 && item1.text === item2.text
  }))
})
Comments