如何比较两个数组,如果找到相同的键,则从第二个数组中获取值并将其分配给第一个数组。结果是使用第一个数组。例如我有下面的数组:
var compareit = {
firstArray : {
'color': 'blue',
'width': 400,
'height': 150,
},
secondArray: {
'color': 'red',
'height': 500,
},
};
目标是,我想要的结果是:{'color': 'red', 'width': '400', 'height': '500'};
我非常感谢您的帮助...谢谢:)
最佳答案
您可以使用 Object.assign()
将值从一个或多个源对象复制到目标对象。
var compareit = {
firstArray: {
'color': 'blue',
'width': 400,
'height': 150,
},
secondArray: {
'color': 'red',
'height': 500,
},
};
Object.assign(compareit.firstArray, compareit.secondArray);
console.log(compareit.firstArray)
如果你不想操作现有对象compareit.firstArray
var compareit = {
firstArray: {
'color': 'blue',
'width': 400,
'height': 150,
},
secondArray: {
'color': 'red',
'height': 500,
},
};
var obj = {};
Object.assign(obj, compareit.firstArray, compareit.secondArray);
console.log(obj, compareit)
关于javascript - 比较两个数组,如果发现相同的键,则从第二个数组中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42201363/