es6合并两个对象数组并覆盖现有对象 [英] es6 merge two array of objects and override the existing object
问题描述
我有2个对象数组:
const arr1 = [{'id':'1' 'value':'yes'}, {'id':'2', 'value':'no'}];
const arr2 = [{'id':'2', 'value':'yes'}];
所以,如果我尝试合并这2个数组,结果应该是:
So, if I try and merge these 2 arrays the result should be:
arrTemp = [{'id':'1', 'value':'yes'}, {'id':'2', 'value':'yes'}];
基本上,它应该类似于Object.assign(),但是无论我尝试什么,它都无法正常工作.有人可以帮我吗?
Basically, it should work similar to Object.assign(), but no matter what I try it does not work. Could anyone please help me in this ?
我修改了数据结构.现在可以合并它们并获得输出了吗?
I modified the data structure. Is it possible to merge them now and get the output.
谢谢
推荐答案
例如,您可以使用有效的ES6数据结构,例如地图:
You could work with a valid ES6 data structure like a map for example:
const 1 = { 1: { string: 'yes' }, 2: { string: 'no' } }
const 2 = { 2: { string: 'yes' }, 3: { string: 'no' } }
const 3 = { ...1, ...2}
const 1 = { 1: { string: 'yes' }, 2: { string: 'no' } }
const 2 = { 2: { string: 'yes' }, 3: { string: 'no' } }
const 3 = { ...1, ...2}
这会将您的第一个参数替换为第二个参数,或者在可能的情况下将它们组合在一起.
只需在您的浏览器中进行尝试,它就容易得多,并且可以提高性能,因为您无需使用findById()
,这是一项昂贵的操作.
This will override your first argument with the second one or just combine them where possible.
Just try it out in your browser it's a lot easier and enhances performance since you will never have to use findById()
which is an expensive operation.
这篇关于es6合并两个对象数组并覆盖现有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!