0

I have an array of objects and within those objects there is a nested object with an array that i am trying to evaluate. It looks something like this:

item = [
{firstName: "John"
 lastName: "Johnson"
 capabilities: {demographic: Array(3), geographic: Array(3), language: Array(2)}
id: "ndja1-234-njk"
state: LA
}
{firstName: "Jane"
 lastName: "Johnson"
 capabilities: {demographic: Array(3), geographic: Array(3), language: Array(2)}
id: "ndsa1-234-njk"
state: TX
}
]

I am trying to filter the list of objects and only return the objects which match the users input for either firstname, lastname, phonenumber, and geographic. But because the geographic is not at the first level of the array I am getting an error that says is is null when i try and filter through it like this:

const newList = (items, value) => {
    let providerList = items.filter(i => i.firstName.includes(value) || i.lastName.includes(value) || i.phone.includes(value) || i.capabilites.geographic.includes(value));
    setSearchResult(providerList)
  };

I believe it is because of the position of the geographic values in the object but im not sure how to handle waiting for it to not be null. This function works until I add the geographic OR statement.

3
  • Are you sure you want includes for checking a string? As 'hello'.includes('o') is true. Commented Oct 20, 2020 at 19:56
  • What would be an alternative to using includes ? I realize now this is not the best logic for this Commented Oct 25, 2020 at 14:39
  • Check that they’re the same? Commented Oct 25, 2020 at 14:40

2 Answers 2

1

Try this solution. That can be the issue coz some objects don't include capabilities in it.

const newList = (items, value) => {
    let providerList = items.filter(i => i.firstName.includes(value) || i.lastName.includes(value) || i.phone.includes(value) || i.capabilites.geographic && i.capabilites.geographic.includes(value));
    setSearchResult(providerList)
  };
Sign up to request clarification or add additional context in comments.

2 Comments

This works! And I understand why, thank you for your response!
You could also use optional chaining like this: i.capabilites.geographic?.includes(value). If it exists, it will call the method, else return undefined
0

You have a typo. Instead of i.capabilites use i.capabilities

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.