0

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

0

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.