如何使用Javascript或lodash对两个对象的属性进行浅层比较? [英] How can I do a shallow comparison of the properties of two objects with Javascript or lodash?

查看:74
本文介绍了如何使用Javascript或lodash对两个对象的属性进行浅层比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以做一个浅表比较,而不会比较Java或lodash对象内部的对象内容?请注意,我确实检查过lodash,但是它似乎执行了我不想做的深层比较.

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 lodash, but it appears to perform a deep comparison which I don't want to do.

var a = { x: 1, y: 2}
var b = { x: 1, y: 3}

是否可以通过某种方式比较 a b ?

Is there some way for example to compare a and b?

推荐答案

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

注意:

  • 因为这很浅,所以 areEqualShallow({a:{}},{a:{}})为假.

areEqualShallow({a:undefined},{})为假.

这包括原型中的所有属性.

This includes any properties from the prototype.

这使用 === 比较.我想那就是你想要的. NaN === NaN 是一种可能会产生意外结果的情况.如果 === 不是您想要的,请替换为您想要的比较.

This uses === comparison. I assume that is what you want. NaN === NaN is one case that may yield unexpected results. If === is not what you want, substitute with the comparison you want.

如果每个对象中都有相同的键,则

If the same keys are in each object, then

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

这篇关于如何使用Javascript或lodash对两个对象的属性进行浅层比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆