Compare objects with array of objects

0

I will try to be practical. For example, I have the following objects:

let a = {
  'before': 'small',
  'after': 'large',
  'type': 'size'
}

let b = [
  {
    'before': 'small',
    'after': 'large',
    'type': 'size'
  },
  {
    'before': 'large',
    'after': 'small',
    'type': 'size'
  }
]

I need to compare them, but since the second is an array of objects, I need to "dismember" it from that array, so that they are two other objects, so I compare the three and return the different and the number of objects different, which in this case is one, but there may be many different cases. I do not know how best to do this, whether it's transforming into arrays and comparing indexes, or if it has a way of comparing it as an object itself.

    
asked by anonymous 25.09.2018 / 17:08

2 answers

1

You can use the Lodash lib.

_.isEqual(value, other)

Performs a deep comparison between two values to determine if they are equivalent.

  

Note : This method supports the comparison of arrays, array buffers,   booleans, date objects, error objects, maps, numbers,   objects, regular expressions, sets, strings, symbols, and   typed arrays. Objects are compared by their own   properties, not inheritable and enumerable. Functions and DOM nodes are   compared by strict equality, ie === .   Source: link

Example

let a = {
  'before': 'small',
  'after': 'large',
  'type': 'size'
}

let b = [{
    'before': 'small',
    'after': 'large',
    'type': 'size'
  },
  {
    'before': 'large',
    'after': 'small',
    'type': 'size'
  }
]
console.log(_.isEqual(a, b));

let c = {
  'before': 'small',
  'after': 'large',
  'type': 'size'
}

let d = {
    'before': 'small',
    'after': 'large',
    'type': 'size'
  }
console.log(_.isEqual(c, d));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
    
25.09.2018 / 18:04
0

I made this example in codepen for what the code would look like.

But what you need to do is just that:

b.filter( item => JSON.stringify(item) !== JSON.stringify(a) )
    
25.09.2018 / 20:07