Cas*_*sey 18 javascript object underscore.js
我试图用下划线比较两个对象.
对象1(过滤器)
{
"tuxedoorsuit":"tuxedoorsuit-tuxedo",
"occasions":"occasions-wedding"
}
Run Code Online (Sandbox Code Playgroud)
对象2(属性)
{
"tuxedoorsuit":"tuxedoorsuit-tuxedo",
"occasions":"occasions-wedding",
"occasions":"occasions-prom",
"product_fit":"product_fit-slim",
"colorfamily":"colorfamily-black"
}
Run Code Online (Sandbox Code Playgroud)
我想在对象2中找到对象1的所有项目时返回true.对此最好的下划线方法是什么?
the*_*eye 27
编辑:根据Arnaldo的评论,你可以使用这样的isMatch功能
console.log(_.isMatch(object2, object1));
Run Code Online (Sandbox Code Playgroud)
描述说,
_.isMatch(object, properties)告诉您属性中的键和值是否包含在对象中.
如果你想自己迭代,只需使用_.keys和_.every,像这样
_.every(_.keys(object1), function(currentKey) {
return _.has(object2, currentKey) &&
_.isEqual(object1[currentKey], object2[currentKey]);
});
Run Code Online (Sandbox Code Playgroud)
或链式版本,
var result = _.chain(object1)
.keys()
.every(function(currentKey) {
return _.has(object2, currentKey) &&
_.isEqual(object1[currentKey], object2[currentKey]);
})
.value();
Run Code Online (Sandbox Code Playgroud)
如果结果是true,则表示所有键object1都在,object2并且它们的值也相等.
这基本上遍历所有键,object1并检查对应于键入object1的值是否等于值object2.
使用underscore.js比较两个对象
**isEqual :** _.isEqual(object, other)
Run Code Online (Sandbox Code Playgroud)
在两个对象之间执行优化的深度比较,以确定它们是否应被视为相等.
例如:
var stooge = {name: 'moe', luckyNumbers: [13, 27, 34]};
var clone = {name: 'moe', luckyNumbers: [13, 27, 34]};
_.isEqual(stooge, clone)
Returns True
Run Code Online (Sandbox Code Playgroud)