比较Javascript/Angular中的2Json对象

Compare 2 Json object in Javascript/Angular

本文关键字:2Json 对象 中的 Angular Javascript 比较      更新时间:2023-09-26

我需要比较两个json对象,如下所示:(这是一个谷歌chrome控制台输出)

    Object {brand: "Marca A", type: "Tipo A", model: "Modelo A", color: "Color A", hand: "Mano A"…}
_id: "534664b081362062015d1b77"
brand: "Marca A"
color: "Color A"
hand: "Mano A"
model: "Modelo A"
price: "11,11"
type: "Tipo A"
__proto__: Object
__defineGetter__: function __defineGetter__() { [native code] }
__defineSetter__: function __defineSetter__() { [native code] }
__lookupGetter__: function __lookupGetter__() { [native code] }
__lookupSetter__: function __lookupSetter__() { [native code] }
constructor: function Object() { [native code] }
hasOwnProperty: function hasOwnProperty() { [native code] }
isPrototypeOf: function isPrototypeOf() { [native code] }
propertyIsEnumerable: function propertyIsEnumerable() { [native code] }
toLocaleString: function toLocaleString() { [native code] }
toString: function toString() { [native code] }
valueOf: function valueOf() { [native code] }
get __proto__: function __proto__() { [native code] }
set __proto__: function __proto__() { [native code] }

我曾经尝试过字符串、angular.equals、下划线,但总是返回false。。我想做一些更复杂的事情,逐一比较Json的字段,有可能吗?

angular。equals(o1,o2)应该完成这项工作,如果结果是false,则某些属性不相等。

是一个上层结构,但非常有用,请尝试在项目中集成"下划线",以比较可以使用的对象http://underscorejs.org/#isEqual.

最简单的方法是使用Stringify JSON.Stringify,它将对象更改为字符串并进行比较。

function isSame(o1, o2)
{
    return JSON.stringify(o1) !== JSON.stringify(o2);
}

然而,对于结构不同的相同JSON对象,此方法将失败,例如:

JSON.stringify({a:1,b:2}) == JSON.stringify({b:2,a:1}) // returns false

为了解决这个问题,你可以使用深度比较,如JavaScript 中对象比较的答案所示

但是,你也可以使用undercore.js,而不是重新发明轮子。它有一个比较对象的函数isEqual()。

_.isEqual(o1, o2);