[Vuejs]-Lodash filter search in few element from array (Vue)

3👍

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>

2👍

You could use pickBy like this:

const knowledges = {1:{name:"Adam",age:12,},2:{name:"Michal",age:14,},3:{name:"Jozef",age:12,}},
      arrayOfNumbers = [1,3],
      result = _.pickBy(knowledges, (v, k) => arrayOfNumbers.includes(+k));

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

In vanilla JS, you could filter the the entries of the object and create an object using Object.fromEntires() like this:

const knowledges={1:{name:"Adam",age:12,},2:{name:"Michal",age:14,},3:{name:"Jozef",age:12,}},
      arrayOfNumbers=[1,3];

const newObject = Object.fromEntries(
    Object.entries(knowledges).filter(([k, v]) => arrayOfNumbers.includes(+k))
)

console.log(newObject)
👤adiga

Leave a comment