为什么_.isEqualWith()无法按预期工作?

时间:2020-03-23 10:51:46

标签: javascript angularjs

我需要比较两个省略$$hashKey属性的相似对象。 为什么不起作用?

        var obj1 = {
            class: '',
            kind: 'nats',
            url: 'http://some.valid',
            $$hashKey: 'object:37'
        };

        var obj2 = {
            class: '',
            kind: 'nats',
            url: 'http://some.valid'
        };

        lodash.isEqualWith(obj1, obj2, function (objectValue, otherValue, key) {
            if (key === '$$hashKey') {
                return true;
            }
        });

注意:我不能为此使用angular.equals()。只有Lodash或香草。

2 个答案:

答案 0 :(得分:3)

使用_.omit()

var obj1 = {
  class: '',
  kind: 'nats',
  url: 'http://some.valid',
  $$hashKey: 'object:37'
};

var obj2 = {
  class: '',
  kind: 'nats',
  url: 'http://some.valid'
};

var ommitted = ['$$hashKey']

var result = _.isEqual(
  _.omit(obj1, ommitted),
  _.omit(obj2, ommitted)
);

console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

答案 1 :(得分:1)

@ User863使用loadash给出了答案,这是纯js中的一种解决方法:

function checkObjEquality(obj1, obj2, keysToIgnore = []) {
  const keysObj1 = Object.keys(obj1).filter(x => !keysToIgnore.length ||
    !keysToIgnore.includes(x));

  const keysObj2 = Object.keys(obj2).filter(x => !keysToIgnore.length ||
    !keysToIgnore.includes(x));

  // There are not the same number of keyx, the objects can't be equals
  if (keysObj1.length !== keysObj2.length) {
    return false;
  }
  
  // one key of Obj1 doesn't exist in Obj2
  if (keysObj1.some(x => !keysObj2.includes(x))) {
    return false;
  }

  // Check that every key have the same value
  return keysObj1.every(x => obj1[x] === obj2[x]);
}

console.log(checkObjEquality({
  class: '',
  kind: 'nats',
  url: 'http://some.valid',
  $$hashKey: 'object:37'
}, {
  class: '',
  kind: 'nats',
  url: 'http://some.valid',
}, ['$$hashKey']));

console.log(checkObjEquality({
  class: '',
  kind: 'NOPE',
  url: 'http://some.valid',
  $$hashKey: 'object:37'
}, {
  class: '',
  kind: 'nats',
  url: 'http://some.valid',
}, ['$$hashKey']));

console.log(checkObjEquality({
  class: '',
  kind: 'nats',
  url: 'http://some.valid',
  $$hashKey: 'object:37'
}, {
  class: '',
  kind: 'nats',
}, ['$$hashKey']));

相关问题