Compare Two Array, if found same key get the value from 2nd Array

て烟熏妆下的殇ゞ 提交于 2020-01-17 07:39:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!