简体   繁体   English

如何从Javascript中的过滤器返回特定值

[英]How to Return Specific Values from a Filter in Javascript

I have an object array 我有一个对象数组

animals[
 {id:1, name:"cat"}, 
 {id:2, name:"dog"}, 
 {id:3, name:"fish"}
]

and i have another 我还有另一个

selected = [1,2]

I want to have a return as a string of selected ones: 我想以所选字符串的形式返回:

"cat, dog"

I currently know how to filter 我目前知道如何过滤

   const selectedAnimals = selected.filter(function(e) {
      return animals.find(o => o.id == e);
    })

But this returns the list of ids. 但这将返回ID列表。 How would I rerturn the list of names and in string format? 如何返回名称列表和字符串格式? Would I need to use reduce or can i do it with the filter option? 我需要使用reduce还是可以使用filter选项?

You are using the filter function backwards. 您正在向后使用过滤器功能。 You should use filter on the animals array. 您应该在animals数组上使用过滤器。 Try this: 尝试这个:

const selectedAnimals = animals.filter(function(e) {
   return selected.find(id => e.id == id);
})

This will give you a list of animal objects with ids, then you can loop over that and extract the name if you want to create an array of just the names. 这将为您提供带有id的动物对象列表,然后如果您要创建仅包含名称的数组,则可以遍历该对象并提取名称。

You have to use filter() on your animals array. 您必须在animals数组上使用filter() Can use includes() to check if array contains given value. 可以使用include()检查数组是否包含给定值。

var selectedAnimals = animals.filter(animal => selected.includes(animal.id));

Live Example: 现场示例:

 var animals = [ {id:1, name:"cat"}, {id:2, name:"dog"}, {id:3, name:"fish"} ]; var selected = [1,2]; var selectedAnimals = animals.filter(animal => selected.includes(animal.id)); console.log(selectedAnimals); 

You can archive that by doing the following 您可以通过以下操作将其存档

let animals = [
 {id:1, name:"cat"}, 
 {id:2, name:"dog"}, 
 {id:3, name:"fish"}
]

let selected = [1,2]

const selectedAnimals = animals.filter(e =>(
      selected.includes(e.id))
    )

and selectedAnimals should have [ {id: 1, name: "cat"}, {id: 2, name: "dog"} ] 并且selectedAnimals应该具有[{{id:1,name:“ cat”},{id:2,name:“ dog”}]

Alternatively, you can use a map but then you will end up with the following. 另外,您可以使用地图,但随后您将获得以下内容。

let selectedAnimals = animals.map((e,t) => { if(selected.includes(e.id)) return e.name; else return null} )

["cat", "dog", null] [“猫”,“狗”,空]

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

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