我有两个json对象,我想将它们相互比较。两者具有相同的值但是顺序不同。现在我在名为angular.equals()
的角度中找到了这个有用的函数,它告诉我对象是否相同,但是我试图找出一种方法,这个函数忽略了值的顺序。例如< / p>
编辑代码
var obj = {{name: "Product 1"}, {name:"Product 2"}, {name:"Product 3"}}
var obj2= {{name: "Product 2"}, {name:"Product 1"}, {name:"Product 3"}}
正如您所看到的,它们的值相同,只是它们的顺序不同。有没有办法让角度忽略顺序?
答案 0 :(得分:0)
你可以使用Lodash的_.isEqual()
示例:
// Extract metadata from the image
Metadata metadata = ImageMetadataReader.readMetadata(image);
// Iterate through any XMP directories we may have received
for (XmpDirectory xmpDirectory : metadata.getDirectoriesOfType(XmpDirectory.class)) {
// Usually with metadata-extractor, you iterate a directory's tags. However XMP has
// a complex structure with many potentially unknown properties. This doesn't map
// well to metadata-extractor's directory-and-tag model.
//
// If you need to use XMP data, access the XMPMeta object directly.
XMPMeta xmpMeta = xmpDirectory.getXMPMeta();
// Iterate XMP properties
XMPIterator itr = xmpMeta.iterator();
while (itr.hasNext()) {
XMPPropertyInfo property = (XMPPropertyInfo) itr.next();
// Print details of the property
System.out.println(property.getPath() + ": " + property.getValue());
}
}
对于纯JavaScript,还有另一个问题:How to compare arrays in JavaScript?
另一种选择是比较字符串:
var arr1 = ["Product 1", "Product 2", "Product 3"];
var arr2 = ["Product 2", "Product 1", "Product 3"];
_.isEqual(arr1, arr2);
答案 1 :(得分:0)
angular.equals(["Product 1", "Product 2", "Product 3"].sort(), ["Product 2", "Product 1", "Product 3"].sort());
请注意,数组已排序,否则将返回false(以及lodash)。此函数会忽略哈希键。
如果数组项是复杂的对象,我们可以通过对象属性对数组进行排序,传递给 sort 函数我们的比较函数:
sort(function (a, b) {
// our comparison code (a.id against b.id for example)
})
angular.equals([{name: "Product 1"}, {name:"Product 2"}, {name:"Product 3"}].sort(function(a,b){return a.name > b.name}), [{name: "Product 2"}, {name:"Product 1"}, {name:"Product 3"}].sort(function(a,b){return a.name > b.name}))
将返回true