比较 Angular 中的对象 [英] Compare objects in Angular
问题描述
是否可以对 Angular 中的两个对象进行深度"比较?我想做的是比较每个键/值对.例如:
Is it possible to do a "deep" comparison of two object in Angular? What I would like to do is compare each key/value pair. For example:
对象 1
{
key1: "value1",
key2: "value2",
key3: "value3"
}
对象 2
{
key1: "value1",
key2: "newvalue",
key3: "value3"
}
我需要的是比较失败,因为只有一个键/值对是不同的.换句话说,所有的键/值对必须完全匹配,否则失败.这是 Angular 中已经内置的东西吗?如果我真的需要,我确信我可以编写自己的服务,但我希望它已经内置.类似于 angular.equals.
What I need is for the comparison to fail since only one of the key/value pairs is diffent. In other words ALL of the key/value pairs must match exactly or else failure. Is this something already built into Angular. I'm sure I could write my own service if I really needed to, but I was hoping it was already built in. Similar to angular.equals.
推荐答案
要比较两个对象,您可以使用:
To compare two objects you can use:
angular.equals(obj1, obj2)
进行深度比较,不依赖于键的顺序参见 AngularJS DOCS 和一点 演示
It does a deep comparison and does not depend on the order of the keys See AngularJS DOCS and a little Demo
var obj1 = {
key1: "value1",
key2: "value2",
key3: {a: "aa", b: "bb"}
}
var obj2 = {
key2: "value2",
key1: "value1",
key3: {a: "aa", b: "bb"}
}
angular.equals(obj1, obj2) //<--- would return true
这篇关于比较 Angular 中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!