简体   繁体   English

如何在 react/javascript 中通过首字母过滤对象数组

[英]How to filter an array of objects by their first letter in react/javascript

I am fairly new to React and javascript environment so some of the syntax and errors don't make sense to me.我对 React 和 javascript 环境相当陌生,所以一些语法和错误对我来说没有意义。 I have tried using the filter function something like this but gives me an error of undefined is not an object.我曾尝试使用过滤器 function 类似的东西,但给我一个undefined is not an object 的错误。

const temp = example.filter(x => x.includes('A'))

Example:例子:

data = [{id: 1, type: Pizza}, {id: 2, type: Taco}, {id: 3, type: Pasta}, {id: 4, type: Sandwich}, {id: 5, type: Pumpkin Pie}]

Output: Output:

temp = [{id: 1, type: Pizza}, {id: 3, type: Pasta}, {id: 5, type: Pumpkin Pie}]

Try to use startWith :尝试使用startWith

 let data = [{id: 1, type: 'Pizza'}, {id: 2, type: 'Taco'}, {id: 3, type: 'Pasta'}, {id: 4, type: 'Sandwich'}, {id: 5, type: 'Pumpkin Pie'}] // Output: let result = data.filter(f => f.type.toLowerCase().startsWith('p')) console.log(result)

The reason your code does not work is because you are not accessing the properties right and trying to match a whole object.您的代码不起作用的原因是您没有访问属性权限并尝试匹配整个 object。 x.includes('A') is doing a comparison with the whole object that is x . x.includes('A')正在与整个 object 进行比较,即x

If you just want to filter the objects in an array based on some specific property in them here's how you can do it.如果您只想根据数组中的某些特定属性过滤数组中的对象,那么您可以这样做。

Sample:样本:

let data = [{id: 1, type: "Pizza"}, {id: 1, type: "Taco"}, {id: 1, type: "Pasta"}, {id: 1, type: "Sandwich"}, {id: 1, type: "Pumpkin Pie"}]

Process:过程:

data.filter(x => x.type.toLowerCase().includes('pizza'))

Output: Output:

[{id: 1, type: Pizza}]

or in your case if you want to just sort by the first letter, you can do:或者在您的情况下,如果您只想按第一个字母排序,您可以这样做:

data.filter(x => x.type.toLowerCase().startsWith('p'))

Returns: [ {id: 1, type: "Pizza"},{id: 1, type: "Pasta"}, {id: 1, type: "Pumpkin Pie"} ]`返回:[ {id: 1, type: "Pizza"},{id: 1, type: "Pasta"}, {id: 1, type: "Pumpkin Pie"} ]`

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

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