问题
An array is as follows :
const arr = [ { name: 'Aditya', hobbies: ['Football', 'Basketball'] },
{ name: 'Amitabh', hobbies: [] },
{ name: 'Akhsara', hobbies: ['Basketball'] },
{ name: 'Aia', hobbies: [] }
];
Using filter function as follows:
public getDatas(hobby) {
const data = _.filter(arr, {hobbies : hobby === 'Unclear' : [] ? [hobby]} );
}
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.
回答1:
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.
You can use Array.prototype.includes like this:
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');
来源:https://stackoverflow.com/questions/53856633/unable-to-filter-the-non-empty-array-data-using-lodash-filter