无法使用lodash过滤器过滤非空数组数据 [英] Unable to filter the non empty array data using lodash filter
本文介绍了无法使用lodash过滤器过滤非空数组数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一个数组如下:
const arr = [ { name: 'Aditya', hobbies: ['Football', 'Basketball'] },
{ name: 'Amitabh', hobbies: [] },
{ name: 'Akhsara', hobbies: ['Basketball'] },
{ name: 'Aia', hobbies: [] }
];
使用过滤器功能如下:
public getDatas(hobby) {
const data = _.filter(arr, {hobbies : hobby === 'Unclear' : [] ? [hobby]} );
}
我有一些方法将Unclear
爱好设置为空数组,当它是Unclear
时,它是不用hobbies : []
返回我的数据,而是返回了整个 arr .
I have some how set the Unclear
hobbies to empty arrays, when it is Unclear
then it is NOT returning me the data with hobbies : []
instead it is returning me the whole of arr.
推荐答案
_.filter
的谓词(第二个参数)指示要过滤的一个或多个属性.由于hobbies
是字符串数组,所以没有hobbies
的hobby
属性.
The predicate (second argument) of _.filter
indicates the property or properties to filter. Since hobbies
is a string array, there is no hobby
property of hobbies
.
您可以使用 Array.prototype.包括,例如:
const data = _.filter(arr, item => item.hobbies.includes('Unclear'));
// If you want to extract just the 'hobbies' object, not the parent
const hobbies = _.map(data, 'hobbies');
这篇关于无法使用lodash过滤器过滤非空数组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文