Compare objects with object array

Asked

Viewed 529 times

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 it’s two other objects, so I compare the three and return the different and the amount of different objects, which in this case is one, but many different cases can come. I don’t know what is the best way to do this, whether it is by transforming into arrays and comparing indices, or whether it has a way to compare as an object.

  • You have a similar question here, see if it helps you: https://answall.com/questions/291203/howto compared-se-dois-objetos-javascript-s%C3%A3o-equals

  • Help to some extent, the problem starts when I have an array of objects to compare, so I don’t know if it is possible to dismember this array into two objects.

2 answers

1

You can use the lib Lodash.

_.isEqual(value, other)

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

Note: This method supports comparison of matrices, matrix buffers, boolean, date objects, error objects, maps, numbers, objects, regular expressions, sets, strings, symbols and typed matrices. Objects are compared by their own properties, not inheritable and enumerable. DOM functions and nodes are compared by strict equality, ie ===. Source: https://lodash.com/docs#isEqual

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>

0

I did this example on codepen what the code would look like.

But what you’d need to do is just that:

b.filter( item => JSON.stringify(item) !== JSON.stringify(a) )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.