javascript es6合并两个对象数组并覆盖现有对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47554688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:28:15  来源:igfitidea点击:

es6 merge two array of objects and override the existing object

javascriptarraysmergeecmascript-6

提问by Ashy Ashcsi

I have 2 array of objects:

我有 2 个对象数组:

const arr1 = [{'id':'1' 'value':'yes'}, {'id':'2', 'value':'no'}];
const arr2 = [{'id':'2', 'value':'yes'}];

So, if I try and merge these 2 arrays the result should be:

所以,如果我尝试合并这两个数组,结果应该是:

arrTemp = [{'id':'1', 'value':'yes'}, {'id':'2', 'value':'yes'}];

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 ?

基本上,它应该与 Object.assign() 类似,但无论我尝试什么,它都不起作用。任何人都可以帮助我吗?

I modified the data structure. Is it possible to merge them now and get the output.

我修改了数据结构。现在是否可以合并它们并获得输出。

Thanks

谢谢

回答by jovi De Croock

You could work with a valid ES6 data structure like a map for example:

您可以使用有效的 ES6 数据结构,例如地图:

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}

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.

这将用第二个参数覆盖您的第一个参数,或者在可能的情况下将它们组合起来。只需在您的浏览器中尝试一下,它会更容易并提高性能,因为您将永远不必使用findById()这是一项昂贵的操作。

回答by Jonas Wilms

const result = Object.entries(Object.assign({}, ...arr1,...arr2)).map(([key, value]) => ({[key]:value}));

You could spread (...) the arrays into one resulting object ( via Object.assign) and then mapits entries to an array again.

您可以将 ( ...) 数组传播到一个结果对象 ( via Object.assign) 中,然后将map其条目再次传播到数组中。

回答by willwoo

In javascript, arrays are simply objects indexed by numbers starting from 0.

在 JavaScript 中,数组只是由从 0 开始的数字索引的对象。

So when you use Object.assignon arr1and arr2you will override the first item in the arr1with the first item in arr2because they are both indexed under the key 0.

因此,当您使用Object.assignon 时arr1arr2您将使用第一个项目覆盖 the 中的第arr1一个项目,arr2因为它们都在 key 下建立索引0

your result will be:

你的结果将是:

[
 { '2': 'yes' },
 { '2': 'no' }
]

(or in object syntax:)

(或在对象语法中:)

{ 
 0: { '2': 'yes' },
 1: { '2': 'no' }
}

Instead of using arrays, you could create an object indexed by the number string(which is how you seem to be thinking of the array in any case).

您可以创建一个由数字字符串索引的对象,而不是使用数组(无论如何,这就是您对数组的看法)。

So you could change your original data structure to make the job easier:

因此,您可以更改原始数据结构以使工作更轻松:

const arr1 = {
  '1': 'yes',
  '2': 'no'
};

const arr2 = {
  '2': 'yes'
};

const result = Object.assign(arr1, arr2);

回答by Madura Pradeep

This is how you can get the job done with ES6 spread, reduce and Object.values.

这就是使用 ES6 spread、reduce 和 Object.values 完成工作的方式。

const arr1 = [{
  'id': '1',
  'value': 'yes'
}, {
  'id': '2',
  'value': 'no'
}];
const arr2 = [{
  'id': '2',
  'value': 'yes'
}];

const result = Object.values([...arr1, ...arr2].reduce((result, {
  id,
  ...rest
}) => {
  result[id] = {
    ...(result[id] || {}),
    id,
    ...rest
  };
  return result;
}, {}));

console.log(result);

回答by Nina Scholz

You could take a Mapas reference to the new assigned object in the result array and build first a new array with a copy of the objects and then iterate the second array and update the objects with the same key.

您可以将 aMap作为对结果数组中新分配对象的引用,并首先使用对象的副本构建一个新数组,然后迭代第二个数组并使用相同的键更新对象。

var array1 = [{ 1: 'yes' }, { 2: 'no' }],
    array2 = [{ 2: 'yes' }],
    getKey = o => Object.keys(o)[0],
    map = new Map,
    result = array1.map(o => (k => map.set(k, Object.assign({}, o)).get(k))(getKey(o)));

array2.forEach(o => Object.assign(map.get(getKey(o)), o));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

回答by Aathi

simple way to add with exist array of object:

添加对象的现有数组的简单方法:

const arr1 = [{ "name":"John", "age":30, "car":"toyata" }];
const arr2 = [{ "name":"Ales", "age":40, "car":"Nissan" }];
Array.prototype.push.apply(arr1, arr2);

Result:=>
console.log(arr1)

回答by visscher

For anyone finding this answer at a later point in time. There are a couple of ways that you could want this to work exactly, but you could filter all adjusted elements in the first array, and then combine it with the second array.

对于稍后找到此答案的任何人。您可以通过多种方式使其完全正常工作,但您可以过滤第一个数组中所有调整后的元素,然后将其与第二个数组组合。

const arr3 = [...arr1.filter(item1 => !arr2.find(item2 => item1.id === item2.id)), ...arr2]

Alternatively, you could update the elements in the first array, and then filter them from the second array instead.

或者,您可以更新第一个数组中的元素,然后从第二个数组中过滤它们。

回答by Augusto

You cannot use array.prototype map because the key of arr1 and arr2 have the same value '2'.

您不能使用 array.prototype 映射,因为 arr1 和 arr2 的键具有相同的值 '2'。

You should use something like this

你应该使用这样的东西

for (var i = 0, l = arr1.length; i < l; i++) {
 var key = Object.keys(arr1[i]);
 if (!arr2[key]) { arr2[key] = []; }
 arr2[key].push(arr1[i][key]);
}

Regards

问候