1

var obj1 = { key1: 'value1', key2: 'value2', key3: [] },
    obj2 = { key1: 'value1', key2: 'someOtherValue', key3: [] },
    map = new Map();

Object.keys(obj1).forEach(k => map.set(k, obj1[k]));
Object.keys(obj2).forEach(k => map.get(k) !== obj2[k] && console.log(k + ' is different'));

I taken the piece of code from how to compare two javascript array using angular.foreach but in my scenario need to add array also in map, So please help me out from this. Thanks.

5
  • so what exactly is the problem? Commented Jul 15, 2020 at 7:40
  • In both object key3 values is same('[]') but in console its getting different. Commented Jul 15, 2020 at 7:41
  • its not the same, they may both have no elements but they are not the same Commented Jul 15, 2020 at 7:42
  • 2
    Does this answer your question? How to compare arrays in JavaScript? Commented Jul 15, 2020 at 7:42
  • Yeah, but how can i check there is no element difference in both Commented Jul 15, 2020 at 7:44

1 Answer 1

1

You could stringify the value to get a comparable value.

The original code checks the value with primitive types. By using objects, the object reference is used for checking. If you have two different arrays, you have two different object references.

var obj1 = { key1: 'value1', key2: 'value2', key3: [] },
    obj2 = { key1: 'value1', key2: 'someOtherValue', key3: [] },
    map = new Map();

Object.keys(obj1).forEach(k => map.set(k, obj1[k]));
Object.keys(obj2).forEach(k => {
    const value = map.get(k);
    if (value !== obj2[k] && JSON.stringify(value) !== JSON.stringify(obj2[k])) {
        console.log(k + ' is different');
    }
});

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

1 Comment

only works if the values of the arrays are supported, ex undefined, function(){}, Symbol('') and null will all be transformed into nulls during JSON.stringify, sets and maps will also be transformed into objects

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.