Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter array of objects by values when not all objects have some keys

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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,

>Solution :

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading