Search code examples
javascriptvue.jslodash

Lodash filter search in few element from array (Vue)


I have an object:

{
   1: {
         name: 'Adam',
         age: 12,
      },
   2: {
         name: 'Michal',
         age: 14,
      },
   3: {
         name: 'Jozef',
         age: 12,
      }
}

I tried using function filter from lodash:

this.knowledges = _.filter(this.knowledges, function (item) {
    if (item.category[1] !== undefined) {
        return arrayOfNumbers.indexOf(item.category[1].category_id) >= 0
    }
})

Variable arrayOfNumbers return array: [1,3] so function filter should return:

{
   1: {
         name: 'Adam',
         age: 12,
      },
   3: {
         name: 'Jozef',
         age: 12,
      }
}

But it returns only first index:

{
   1: {
         name: 'Adam',
         age: 12,
      }
}

How can I fix it ?


Solution

  • With lodash you can use _.pick(). Pick takes an object, and an array of properties, and generates a new object with the selected properties:

    const knowledges = {1:{name:"Adam",age:12,},2:{name:"Michal",age:14,},3:{name:"Jozef",age:12,}}
    const arrayOfNumbers = [1,3]
    
    const result = _.pick(knowledges, arrayOfNumbers)
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

    The _.pickBy() method works identically to filter for objects, so you can query the objects values, when you decide what to keep.

    In this examples, I use _.pickBy() to keep all items with age === 12:

    const knowledges = {1:{name:"Adam",age:12,},2:{name:"Michal",age:14,},3:{name:"Jozef",age:12,}}
    
    const result = _.pickBy(knowledges, o => o.age === 12)
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>