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

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

    const shallowEq = (a, b) =>
      [...Object.keys(a), ...Object.keys(b)].every((k) => b[k] === a[k]);
    

    If you really need to check undefined values, then this extension should satisfy @AndrewRasmussen:

    const shallowEq2 = (a, b) =>
      [...Object.keys(a), ...Object.keys(b)].every(k => b[k] === a[k] && a.hasOwnProperty(k) && b.hasOwnProperty(k)); 
    

    In most use cases you don't really need all the checks, and you only want to see if b contains everything a contains. Then an a-centric check would be really really terse:

    const shallowEq3 = (a, b) => Object.keys(a).every(k => b[k] === a[k]);
    

提交回复
热议问题