0

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": "[email protected]",
    "body": "laudantium enim quasi est quidem magnccusantium"
  },
  {
    "postId": 1,
    "id": 2,
    "name": "quo vero reiciendis velit similique earum",
    "email": "[email protected]",
    "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?

6
  • It's better to have a dropdown alongside, let user the key by which they want to search and then search for that key for the particular value Commented Oct 23, 2019 at 17:08
  • Ah I see. But, is there a way I can search the entire table ( array of objects ) irrespective of the key based on user entered input string? @CodeManiac Commented Oct 23, 2019 at 17:10
  • Yes you can, you need to search loop though all the entries and use some method if any of the value matches then you can return that element, Commented Oct 23, 2019 at 17:12
  • 1
    Try const filteredData = data.filter(item => Object.values(item).some(val => val.toString().includes(searchTerm.value))) Commented Oct 23, 2019 at 17:16
  • OMG! That was it man. Appreciate it! @David Can you post it as a answer so that I can accept it. Commented Oct 23, 2019 at 17:19

1 Answer 1

3

Try this:

const filteredData = data.filter(item => Object.values(item).some(val => val.toString().includes(searchTerm.value)));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.