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.

Bikash Pandit
  • 48
  • 1
  • 9

1 Answers1

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');
    }
});
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 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 – Krzysztof Krzeszewski Jul 15 '20 at 07:46