1

I am trying to filter an array of objects based on user input.

I wish filter based on the values of certain keys within the object. However, not all the objects have all keys inside them. This means when I check it throws an error.

How do I ignore if a particular object does not have one of the keys inside it and continues to output the matching objects?

Here is some sample data.

const data = [
{
    name: "John Miller",
    age: 33,
    location: "Chicago",
    address: '1 help street'
},

{
    name: "Jane Doe",
    age: 78,
    address: '1 help me please lane'
},

{
    name: "Jamie Stevens",
    location: "San Diego",
    age: 32
}
]

The second object does not have 'location' as a key and the third object does not have 'address' as a key.

const handleSearch = (query) => {
    const keys = ['name', 'location', 'address']
    const filter =  data.filter((row) => (
      keys.some((key) => (row[key].toLowerCase().includes(query))
    )))
    setFilteredData(filter)
  }

Thank you,

0

2 Answers 2

2

You can combine optional chaining with the nullish coalescing operator:

const handleSearch = (query) => {
  const keys = ['name', 'location', 'address']
  const filter = data.filter((row) => (
    keys.some((key) => {
        const k = row?.[key] ?? ''
        return (k.toLowerCase().includes(query))
      }
    )))
  setFilteredData(filter)
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use the optional chaining operator(?.) and you also need to lower case the query:

const data = [
  {
    name: "John Miller",
    age: 33,
    location: "Chicago",
    address: "1 help street",
  },

  {
    name: "Jane Doe",
    age: 78,
    address: "1 help me please lane",
  },

  {
    name: "Jamie Stevens",
    location: "San Diego",
    age: 32,
  },
];

const handleSearch = (query) => {
  const keys = ["name", "location", "address"];
  const filtered = data.filter((row) =>
    keys.some((key) => { 
      return row[key]?.toLowerCase().includes(query.toLowerCase())})
  );
  console.log(filtered);
};

handleSearch("Chicago")

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.