简体   繁体   English

从另一个数组过滤对象数组

[英]Filter array of object from another array

I have two arrays.我有两个数组。 I want to filter one array which contains objects from another array.我想过滤一个包含来自另一个数组的对象的数组。

let array1= [{date:1, count:4}, {date:3, count:6}];
let array2= [1,2,3,4];

After filtering these two arrays, I need filtered arrays as below.过滤这两个数组后,我需要过滤数组,如下所示。

let array= [4,0,6,0];

So, the filtered array contains the count for matched date and zero for unmatched values.因此,过滤后的数组包含匹配日期的计数和不匹配值的零。 But I'm getting only matched data.但我只得到匹配的数据。

Here is my code:这是我的代码:

let array = _.map(_.filter(array1, function(o){
    return _.includes(array2, o.date);
}), 'count');

Thank you谢谢

You can use map() and find() methods for this.您可以为此使用map()find()方法。 You don't need filter() because for each element you will return count or 0 so you can just use map() .您不需要filter()因为对于每个元素,您将返回 count 或 0 ,因此您可以只使用map()

 let array1= [{date:1, count:4}, {date:3, count:6}]; let array2= [1,2,3,4]; var array = array2.map(function(e) { var f = array1.find(a => a.date == e); return f ? f.count : 0 }); console.log(array)

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

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