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

后端 未结 8 1892
爱一瞬间的悲伤
爱一瞬间的悲伤 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:33

    Paul Draper's solution can be optimized by removing the compare in the second pass.

    function areEqualShallow(a, b) {
      for (let key in a) {
        if (!(key in b) || a[key] !== b[key]) {
          return false;
        }
      }
      for (let key in b) {
        if (!(key in a)) {
          return false;
        }
      }
      return true;
    }

    0 讨论(0)
  • 2021-01-01 12:33
    var a = { x: 1, y: 2}
    var b = { x: 1, y: 3}
    
    function shalComp (obj1, obj2) {
     var verdict = true;
     for (var key in obj1) {
      if (obj2[key] != obj1[key]) {
       verdict = false;
      }
     }
     return verdict;
    }
    
    0 讨论(0)
提交回复
热议问题