使用underscore.js比较两个对象 [英] Using underscore.js to compare two Objects
问题描述
我正在尝试用下划线比较两个对象。
I'm trying to compare two objects with underscore.
对象1(过滤器)
{
"tuxedoorsuit":"tuxedoorsuit-tuxedo",
"occasions":"occasions-wedding"
}
对象2(属性)
{
"tuxedoorsuit":"tuxedoorsuit-tuxedo",
"occasions":"occasions-wedding",
"occasions":"occasions-prom",
"product_fit":"product_fit-slim",
"colorfamily":"colorfamily-black"
}
我想在对象2中找到对象1的所有项目时返回true。对此最好的下划线方法是什么?
I want to return true when all items of Object 1 are found within Object 2. What would be the best underscore method to use for this?
推荐答案
编辑按 Arnaldo的评论,你可以使用 isMatch
功能,像这样
As per Arnaldo's comment, you can use isMatch
function, like this
console.log(_.isMatch(object2, object1));
描述说明,
_。isMatch(对象,属性)
告诉您<中的键和值是否为属性包含在对象中。
如果您想自己迭代,只需使用 _。keys
和 _。每个
,就像这样
If you want to iterate yourself, just use _.keys
and _.every
, like this
_.every(_.keys(object1), function(currentKey) {
return _.has(object2, currentKey) &&
_.isEqual(object1[currentKey], object2[currentKey]);
});
或链式版本,
var result = _.chain(object1)
.keys()
.every(function(currentKey) {
return _.has(object2, currentKey) &&
_.isEqual(object1[currentKey], object2[currentKey]);
})
.value();
如果结果为 true
,则表示 object1
中的所有键都在 object2
中,它们的值也相等。
If the result is true
, it means that all the keys in object1
are in object2
and their values are also equal.
这基本上遍历 object1
的所有键,并检查对应于 object1 $ c中的键的值$ c>等于
object2
中的值。
This basically iterates through all the keys of object1
and checks if the value corresponding to the key in object1
is equal to the value in object2
.
这篇关于使用underscore.js比较两个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!