最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to filter an array of objects by their first letter in reactjavascript - Stack Overflow

programmeradmin8浏览0评论

I am fairly new to React and javascript environment so some of the syntax and errors don't make sense to me. I have tried using the filter function something like this but gives me an error of 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:

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

I am fairly new to React and javascript environment so some of the syntax and errors don't make sense to me. I have tried using the filter function something like this but gives me an error of 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:

temp = [{id: 1, type: Pizza}, {id: 3, type: Pasta}, {id: 5, type: Pumpkin Pie}]
Share Improve this question edited Jun 6, 2020 at 23:46 Rachid O 14.1k16 gold badges70 silver badges94 bronze badges asked Jun 6, 2020 at 20:20 Shalin PatelShalin Patel 1793 silver badges13 bronze badges 1
  • 1 Hi, please format your code a bit better. :) – Danyal Commented Jun 6, 2020 at 20:36
Add a ment  | 

2 Answers 2

Reset to default 4

Try to use 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. x.includes('A') is doing a parison with the whole object that is 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:

[{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"} ]`

发布评论

评论列表(0)

  1. 暂无评论