Skip to content Skip to sidebar Skip to footer

Compare Two Array, If Found Same Key Get The Value From 2nd Array

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

Solution 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)

Solution 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);

Solution 3:

var compareit = {
            firstArray : {
                'color': 'blue',
                'width': 400,
                'height': 150,
            },
            secondArray: {
                'color': 'red',
                'height': 500,
            },
    };
var result,
    compareObjects=function(comp){
      returnObject.assign(comp.firstArray, comp.secondArray);
    };

result=compareObjects(compareit);
console.log(result);

Post a Comment for "Compare Two Array, If Found Same Key Get The Value From 2nd Array"