问题
How to compare two arrays, and if found the same key and then get the value from 2nd array and assign it to first array. And the result is using first array. for example I have the array below:
var compareit = {
firstArray : {
'color': 'blue',
'width': 400,
'height': 150,
},
secondArray: {
'color': 'red',
'height': 500,
},
};
The goal is, I want the result will : {'color': 'red', 'width': '400', 'height': '500'};
I really appreciate with any help...Thank you :)
回答1:
You can just use Object.assign() to copy values from one or more source objects to a target object.
var compareit = {
firstArray: {
'color': 'blue',
'width': 400,
'height': 150,
},
secondArray: {
'color': 'red',
'height': 500,
},
};
Object.assign(compareit.firstArray, compareit.secondArray);
console.log(compareit.firstArray)
If you don't want to manipulate existing object 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)
回答2:
You can loop through the properties in the first array, and check if the same property exists in the second array.
var compareit = {
firstArray: {
'color': 'blue',
'width': 400,
'height': 150,
},
secondArray: {
'color': 'red',
'height': 500,
},
};
var result = {};
for (var key in compareit.firstArray) {
if (key in compareit.secondArray) {
result[key] = compareit.secondArray[key];
} else {
result[key] = compareit.firstArray[key];
}
}
console.log(result);
回答3:
var compareit = {
firstArray : {
'color': 'blue',
'width': 400,
'height': 150,
},
secondArray: {
'color': 'red',
'height': 500,
},
};
var result,
compareObjects=function(comp){
return Object.assign(comp.firstArray, comp.secondArray);
};
result=compareObjects(compareit);
console.log(result);
来源:https://stackoverflow.com/questions/42201363/compare-two-array-if-found-same-key-get-the-value-from-2nd-array