1

I want to filter users by name and or lastname. but I´m getting

TypeError: Cannot read property 'toLowerCase' of undefined


const users = [{name: 'john', lastname: "doe"}, {name: 'mary'}]

let searchName = "jo"
let searchLastName = ""

users.filter((user) =>
    user.name
        .toLowerCase()
        .includes(searchName.toLowerCase())

    && user.lastname
        .toLowerCase()
        .includes(searchLastName.toLowerCase())
)

how can I check for lastname only if user has lastname. (i know they always have name)

1

2 Answers 2

4

Variant A: lastName check only if lastName is set:

users.filter((user) =>
    user.name
        .toLowerCase()
        .includes(searchName.toLowerCase())

    && (
        !user.lastname
        || user.lastname
            .toLowerCase()
            .includes(searchLastName.toLowerCase())
    )
)

Variant B: additional condition that lastName must be set:

users.filter((user) =>
    user.name
        .toLowerCase()
        .includes(searchName.toLowerCase())

    && user.lastname
    && user.lastname
        .toLowerCase()
        .includes(searchLastName.toLowerCase())
    )
)
Sign up to request clarification or add additional context in comments.

3 Comments

Whether you want A or B depends on your use case. Both should avoid the TypeError.
&& and || expressions evaluate their operands as boolean values, so user.lastName gets converted to a boolean value (true / false) first. As Pac0 wrote, empty strings, null or undefined are converted to false, but other values are also Falsy values
I will go with option A it works fine with !searchLastName || .... thanks!
3

You can add a check on the existence of the variable with JS automatic boolean coercion :

&& user.lastname   // This will return false if empty, null or undefined
&& user.lastname
    .toLowerCase()
    .includes(searchLastName.toLowerCase())

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.