Unable to filter the non empty array data using lodash filter

老子叫甜甜 提交于 2019-12-11 07:19:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!