下划线JS:比较两个数组



我目前有两个数组,我想与一个和另一个进行比较:

阵列一:

var allCategories =
[
 { utilization:"license", id:"450", type: "MainCategory" },
 { utilization:"rating", id:"451", type: "SubCategory" },
 { utilization:"medical", id:"452", type: "MainCategory" },
 { utilization:"other", id:"453", type: "MainCategory" }
];

阵列二:

var allKinds = 
[
 { name:"name1", id:"450", type: "FAA" },
 { name:"name2", id:"451", type: "FAA" },
 { name:"name3", id:"451", type: "FAA" },
 { name:"name4", id:"451", type: "FAA" },
 { name:"name5", id:"451", type: "SPA" },
 { name:"name6", id:"451", type: "SPA" },
 { name:"name7", id:"452", type: "FBC" },
 { name:"name8", id:"453", type: "SPA" }
];

我正在尝试做的是从"阵列二"中检索项目与利用率进行比较:"许可证","医疗"和"其他"。

目前我已经从"数组一"中提取了 ID,如下所示:

var categories = _.filter(allCategories, function(obj) {
  return obj.utilization === 'license' || obj.utilization === 'medical' || obj.utilization === 'other';
});
var category_ids = _.pluck(categories, 'id');

第二部分,我似乎想不通:如何将"数组一"[450, 452, 453]的结果与"数组二"中的项目进行比较,以检索带有 id 的项目。

这是一个jsfiddle:https://jsfiddle.net/7n9pjrc9/

一个简单的

解决方案是通过检查category_ids是否包含对象id来过滤列表:

var r1 = _.filter(allKinds, function(o) {
    return _.contains(category_ids, o.id);
});
console.log(r1);

或者,如果您愿意,可以过滤所选 ID 的哈希值

var hashed = {};
_.each(categories, function(o) {
    hashed[o.id] = true;
});
var r2 = _.filter(allKinds, function(o) {
    return hashed[o.id];
});
console.log(r2);

和一个演示

var allCategories =
[
 { utilization:"license", id:"450", type: "MainCategory" },
 { utilization:"rating", id:"451", type: "SubCategory" },
 { utilization:"medical", id:"452", type: "MainCategory" },
 { utilization:"other", id:"453", type: "MainCategory" }
];
var allKinds = 
[
 { name:"name1", id:"450", type: "FAA" },
 { name:"name2", id:"451", type: "FAA" },
 { name:"name3", id:"451", type: "FAA" },
 { name:"name4", id:"451", type: "FAA" },
 { name:"name5", id:"451", type: "SPA" },
 { name:"name6", id:"451", type: "SPA" },
 { name:"name7", id:"452", type: "FBC" },
 { name:"name8", id:"453", type: "SPA" }
];
var categories = _.filter(allCategories, function(obj) {
  return obj.utilization === 'license' || obj.utilization === 'medical' || obj.utilization === 'other';
});
var category_ids = _.pluck(categories, 'id');
var r1 = _.filter(allKinds, function(o) {
	return _.contains(category_ids, o.id);
});
console.log(r1);
var hashed = {};
_.each(categories, function(o) {
	hashed[o.id] = true;
});
var r2 = _.filter(allKinds, function(o) {
	return hashed[o.id];
});
console.log(r2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

相关内容

  • 没有找到相关文章

最新更新