Peter Chimp
Peter Chimp

Reputation: 137

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

Upvotes: 0

Views: 2239

Answers (3)

Satpal
Satpal

Reputation: 133403

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)

Upvotes: 1

LellisMoon
LellisMoon

Reputation: 5020

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

Upvotes: 0

Barmar
Barmar

Reputation: 781058

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

Upvotes: 1

Related Questions