3

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);
                    }
                })
            }
George Kagan
  • 5,913
  • 8
  • 46
  • 50
StevieB
  • 6,263
  • 38
  • 108
  • 193
  • 1
    *"I feel I am missing some es6 magic"* not really, but that's not the correct use of `find`. The callback should return `true` or `false`, `.find` will then return the matching value or `null`. The way you use it, you should use `forEach`. Also, iterating over `arrayTwo` would probably make more sense. – Felix Kling Nov 12 '16 at 19:09
  • @Felix gotcha thanks that good feedback – StevieB Nov 12 '16 at 19:11

2 Answers2

3

It is

arrayOne = arrayOne.map(item1 => {
  return Object.assign(item1, arrayTwo.find(item2 => {
    return item1.text === item2.text
  }))
})
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
1

I answered something similar in JavaScript merging objects by id

However, since you want to update one of the initial arrays, and you say the other one is a subset, you can improve it to

let arrayOne = [{text:"one", value:0},{text:"two", value:0}]
let arrayTwo = [{text:"two", value:5}]
var hash = Object.create(null);
arrayOne.forEach(obj => hash[obj.text] = obj);
arrayTwo.forEach(obj => Object.assign(hash[obj.text], obj));
console.log(arrayOne);

The cost is only linear on average, O(arrayOne.length) to fill the hash and O(arrayTwo.length) for the assignments, assuming few properties for each object.

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513