【问题标题】:Lodash equals and omit not working properlyLodash 等于并省略不能正常工作
【发布时间】:2020-12-23 12:15:39
【问题描述】:

我有 2 个 JSON 对象,我必须检查它们是否有任何更改。

它们是相同的,但这个属性不一样,所以 _.equals 返回 false,所以它们不相等

第一个对象:

this.board['children'] = [
    {
        ...
        isSelected: true
        ...
    },
    
    {
        ...
        isSelected: false
        ...
    }
];

第二个对象:

odataElement['children'] = [
    {
        ...
        isSelected: false
        ...
    },
    
    {
        ...
        isSelected: false
        ...
    }
]

所以我尝试了这个函数来省略 isSelected 属性:

var result = _.isEqualWith(this.board['children'], odataElement['children'], this.customizer);

customizer = function (objValue, othValue) {
    let arrayOfEquals = [];
    for(let i = 0; i < objValue.length; i++) {
        arrayOfEquals.push(
            _.isEqual(
                _.omit(objValue[i], ['isSelected']),
                _.omit(othValue[i], ['isSelected'])
            )
        );
    }
    return !_.includes(arrayOfEquals, false) ? true : false;
}

但是好像没有省略isSelected属性,总是假的。

有什么提示吗?谢谢!

【问题讨论】:

  • this.board['children'] 是对象还是数组?
  • 请包含实际的对象数组。
  • 是一个对象数组!

标签: javascript lodash


【解决方案1】:

您可以使用_.isEqualWith() 并通过始终返回true 来忽略此键:

const boardChildren = [{ isSelected: true }, { isSelected: false }]
const odataElementChildren = [{ isSelected: false }, { isSelected: false }]

const result = _.isEqualWith(boardChildren, odataElementChildren, (v1, v2, key) => key === 'isSelected' ? true : undefined)

console.log(result)
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多