How can I do a shallow comparison of the properties of two objects with Javascript or lodash?

后端 未结 8 1925
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 11:31

Is there a way I can do a shallow comparison that will not go down and compare the contents of objects inside of objects in Javascript or lodash? Note that I did check lodas

8条回答
  •  南方客
    南方客 (楼主)
    2021-01-01 12:21

    Simple ES6 approach:

    const shallowCompare = (obj1, obj2) =>
      Object.keys(obj1).length === Object.keys(obj2).length &&
      Object.keys(obj1).every(key => obj1[key] === obj2[key]);
    

    Here I added the object keys amount equality checking for the following comparison should fail (an important case that usually does not taken into the account):

    shallowCompare({ x: 1, y: 3}, { x: 1, y: 3, a: 1}); // false
    

    2019 Update. Per Andrew Rasmussen' comment we also need to take into account undefined case. The problem with the previous approach is that the following comparison returns true:

    ({ foo: undefined })['foo'] === ({ bar: undefined })['foo'] // true
    

    So, explicit keys existence check is needed. And it could be done with hasOwnProperty:

    const shallowCompare = (obj1, obj2) =>
      Object.keys(obj1).length === Object.keys(obj2).length &&
      Object.keys(obj1).every(key => 
        obj2.hasOwnProperty(key) && obj1[key] === obj2[key]
      );
    

提交回复
热议问题