简体   繁体   中英

How do I filter the data based on search input from array of objects in React, ES6

I have the JSON data pattern coming from API in the below way. I was able to filter the data with body key. I'm trying to implement the search functionality which should search all the array of objects irrespective of key based on user input. Could someone please guide how to achieve this. I tried using nested for loop to get the individual key but not luck.

[
  {
    "postId": 1,
    "id": 1,
    "name": "id labore ex et quam laborum",
    "email": "Eliseo@gardner.biz",
    "body": "laudantium enim quasi est quidem magnccusantium"
  },
  {
    "postId": 1,
    "id": 2,
    "name": "quo vero reiciendis velit similique earum",
    "email": "Jayne_Kuhic@sydney.com",
    "body": "est natus enim nihil est dolore is et"
  }
  ...
]

Key based search logic that I'm currently using

const filteredData = data.filter(item =>
      item.body.includes(searchTerm.value)
    );
    this.setState({ filteredData: filteredData });

I created a working example using Sandbox . Could anyone please guide how to achieve the Search results from entire array of Objects?

Try this:

const filteredData = data.filter(item => Object.values(item).some(val => val.toString().includes(searchTerm.value)));

item => { Let foundMatchedKey = item.keys.find(key => item[key].includes(searchTearm.value) If(foundMatchedKey) { return true} else { return false } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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