Lodash isEqual - 如何获取不同对象的键

Lodash isEqual - How to get keys of objects that differ

我正在尝试获取一组键,这些键因比较两个对象而不同。我只能使用 isEqualWithmapKeys 来做到这一点,就像这样:

const differencies = [];
const objA = {
  a: 1,
  b: 2,
  c: 3
};
const objB = {
  a: 1,
  b: 2,
  c: 100
};

function customizer(objOne, objTwo) {
  if (lodash.isEqual(objOne, objTwo)) {
    return true;
  }

  lodash.mapKeys(objOne, (value, key) => {
    if (value !== objTwo[key]) {
      differencies.push(key);
    }
  });

  return false;
}

lodash.isEqualWith(objA, objB, customizer);
console.log(differencies);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<script>const lodash = _;</script>

问题是是否有更好的方法来获取使用 lodash 的不同对象的键?

由于您只需要比较键相同但值可能不同的对象,您可以利用 keys() or keysIn() (if you want to also traverse the prototype chain) and remove all entries that do not have a matching value with filter().

const objA = { a: 1, b: 2, c: 4 };
const objB = { a: 1, b: 2, c: 100 };

const differencies = lodash.filter(
  lodash.keys(objA), 
  key => objA[key] !== objB[key]
);
console.log(differencies);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<script>const lodash = _;</script>

或者使用 chaining syntax:

const objA = { a: 1, b: 2, c: 4 };
const objB = { a: 1, b: 2, c: 100 };

const differencies = lodash(objA)
  .keys()
  .filter(key => objA[key] !== objB[key]);
console.log(differencies);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<script>const lodash = _;</script>

对于这种功能,Lodash 可能有点矫枉过正。简单的 JavaScript 等价于 Object.keys() and Array#filter():

const objA = { a: 1, b: 2, c: 4 };
const objB = { a: 1, b: 2, c: 100 };

const differencies = Object.keys(objA)
  .filter(key => objA[key] !== objB[key]);
console.log(differencies);