简体   繁体   中英

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);
                    }
                })
            }

It is

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM