简体   繁体   English

过滤两个不同的结构化数组下划线js

[英]Filter two different structured arrays underscore js

I have two arrays: 我有两个数组:

array1 = [{Name: 'abc', ID: 23},{Name:'xyz', ID: 10},{Name:'def', ID: 12}];
array2 = [10,23];

Resultant array should be part of array 1 whose ID intersects with contents of array2. 结果数组应该是其ID与array2的内容相交的数组1的一部分。

Here, the result would be result = [{Name: 'abc', ID: 23},{Name: 'xyz', ID:10}] ; 在这里,结果将是result = [{Name: 'abc', ID: 23},{Name: 'xyz', ID:10}] ;

Any ideas how I could achieve this using underscore js? 有什么想法可以使用下划线js实现吗?

_.filter(array1, function(item){ return _.contains(array2, item.ID); });

You can use filter and contains . 您可以使用filtercontains

Try it out here ! 在这里尝试!

Assuming your IDs are unique: 假设您的ID是唯一的:

var groupedById = _.indexBy(array1, "ID");
var filteredArray = _.map(array2, function (lookupId) {
    return groupedById[lookupId];
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM