JS / Es6如何合并两个数组并覆盖其对象中的值

时间:2021-03-18 12:14:06

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.

所以arrayOne将始终是我想要的整个对象集,但是所有值都是0. arrayTwo将具有此数组的子集,但始终具有值集。我想要的是如下,如果arrayOne中存在arrayTwo对象,则将值复制到arrayOne对象。

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.

我做了这样的事,但我觉得我错过了一些es6魔法。

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

2 个解决方案

#1


1  

It is

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

#2


1  

I answered something similar in JavaScript merging objects by id

我在JavaScript中通过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.

假设每个对象的属性很少,成本只是平均线性的,O(arrayOne.length)用于填充哈希值和O(arrayTwo.length)用于赋值。

#1


1  

It is

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

#2


1  

I answered something similar in JavaScript merging objects by id

我在JavaScript中通过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.

假设每个对象的属性很少,成本只是平均线性的,O(arrayOne.length)用于填充哈希值和O(arrayTwo.length)用于赋值。