简体   繁体   English

Lodash过滤器从数组(Vue)中搜索少量元素

[英]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: 我尝试使用lodash中的函数filter

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: 变量arrayOfNumbers返回数组: [1,3]因此函数过滤器应返回:

{
   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 ? 我该如何解决?

You could use pickBy like this: 您可以像这样使用pickBy

 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: 在香草JS中,您可以过滤对象的条目并使用Object.fromEntires()创建对象,如下所示:

 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) 

With lodash you can use _.pick() . 使用lodash可以使用_.pick() Pick takes an object, and an array of properties, and generates a new object with the selected properties: Pick接受一个对象和一个属性数组,并生成一个具有所选属性的新对象:

 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. _.pickBy()方法的工作原理与过滤对象相同,因此,在确定保留内容时,可以查询对象的值。

In this examples, I use _.pickBy() to keep all items with age === 12 : 在此示例中,我使用_.pickBy()来保留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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM