[英]Using underscore.js to compare two Objects
我试图用下划线比较两个对象。
对象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。对此最好的下划线方法是什么?
编辑:根据Arnaldo的评论 ,您可以使用isMatch
函数,就像这样
console.log(_.isMatch(object2, object1));
描述说,
_.isMatch(object, properties)
告诉您属性中的键和值是否包含在对象中。
如果你想自己迭代,只需使用_.keys
和_.every
,就像这样
_.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
并且它们的值也相等。
此通过的所有的键基本上迭代object1
并检查对应于该键的值object1
是等于值object2
。
使用underscore.js比较两个对象
**isEqual :** _.isEqual(object, other)
在两个对象之间执行优化的深度比较,以确定它们是否应被视为相等。
例如:
var stooge = {name: 'moe', luckyNumbers: [13, 27, 34]};
var clone = {name: 'moe', luckyNumbers: [13, 27, 34]};
_.isEqual(stooge, clone)
Returns True
基于以前的功能创建简单的安慰功能:
var compareMe = function (obj1, obj2, parentKey) {
parentKey = parentKey || '';
_.each(_.keys(obj1), function (key) {
if(_.isObject(obj1[key]) ) {
compareMe(obj1[key], obj2[key], parentKey + key + '.')
} else {
if (!_.has(obj2, key) || !_.isEqual(obj1[key], obj2[key])) {
console.log(parentKey + key, obj1[key], obj2[key]);
}
}
})
};
并调用如:compareMe(obj1,obj1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.