JavaScript - Cannot read property 'toLowerCase' of undefined

Viewed 6190

Can't find the problem, but it keeps showing this error!! same happens when using other methods like includes.

let notes = [{},{
    title: 'My next trip',
    body: 'I would like to go to Spain'
},{
    title: 'Habits to work on',
    body: 'Exercise. Eating a bit better'
},{
    title: 'Office modification',
    body: 'Get a new seat'
}]

let filteredNotes = notes.filter( function (note, index) {
    let findFileredTitle = note.title.toLowerCase().includes('ne')
    let findFileredBody = note.body.toLowerCase().includes('ne')

    return findFileredTitle || findFileredBody
})
console.log(filteredNotes)

6 Answers

Your array notes contains four elements. The first one empty. See the empty pair of braces?

let notes = [{}, {

When you later access it:

note.title.toLowerCase() === ...

Then note.title is undefined and you get the error message.

Most likely, you want to remote the empty pair of braces.

There is an object with no property title, because of that you're getting that error. It's something like:

undefined.toLowercase()
        ^

You can add a checking part on note.title as follow:

note.title && (note.title.toLowercase() === .........)
     ^ 

Update your filter method to check if key exists then going for match other return false.

let filteredNotes = notes.filter( function (note, index) {
    let findFileredTitle = note.title && note.title.toLowerCase().includes('ne')
    let findFileredBody = note.body && note.body.toLowerCase().includes('ne')

    return findFileredTitle || findFileredBody
});

Issue : ERROR Error: Uncaught (in promise): TypeError: field.label is undefined

Solution

field.label && field.label.toLowerCase()

Note

  • First check field.label before accessing toLowerCase property

You need to provide null check before converting tilte and body to lowercase.

let notes = [{},{
    title: 'My next trip',
    body: 'I would like to go to Spain'
},{
    title: 'Habits to work on',
    body: 'Exercise. Eating a bit better'
},{
    title: 'Office modification',
    body: 'Get a new seat'
}]

let filteredNotes = notes.filter(function (note, index) {
  let findFileredTitle = '';
    if(note.title){
      findFileredTitle = note.title.toLowerCase().includes('ne')
    }
    let findFileredBody = '';
    if(note.body){
      findFileredBody = note.body.toLowerCase().includes('ne');
    }

    return findFileredTitle || findFileredBody
})
console.log(filteredNotes)

Remove An empty '{}' object from array , note.title is null/Empty so it return error

let notes = [{
    title: 'My next trip',
    body: 'I would like to go to Spain'
},{
    title: 'Habits to work on',
    body: 'Exercise. Eating a bit better'
},{
    title: 'Office modification',
    body: 'Get a new seat'
}]
Related