Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript error: Cannot read property 'includes' of undefined

I want to check if a data.objectId already exists in the array msgArr. For that I am running the code below:

var exists = msgArr.objectId.includes(data.objectId);

if(exists === false){
   msgArr.push({"objectId":data.objectId,"latLont":data.latLont,"isOnline":data.isOnline});
}

The array looks like the following:

var msgArr = [
  {isOnline:true,latLont:"123",objectId:"on0V04v0Y9"},
  {isOnline:true,latLont:"1",objectId:"FpWBmpo0RY"},
  {isOnline:true,latLont:"48343",objectId:"Qt6CRXQuqE"} 
 ]

I am getting the error below:

Cannot read property 'includes' of undefined

like image 566
Folky.H Avatar asked Jan 06 '17 18:01

Folky.H


2 Answers

As the comments say: the javascript array object has no property objectId.
Looking at the objects in this array it's clear that they have it, so to check if a certain element exists you can do so using Array.prototype.some method:

var exists = msgArr.some(o => o.objectId === data.objectId);
like image 74
Nitzan Tomer Avatar answered Nov 09 '22 16:11

Nitzan Tomer


It's telling you that you're trying to access a property on an undefined object. The msgArr object doesn't have a property objectID at all, which means it's undefined. Since that doesn't exist, there's no way for it to have an includes property available of any type.

What you need is to access an object in the array, not the array itself. Something like msgArr[0].objectID would refer to an instantiated object. You could even use the array functions to check if something exists based on its objectID with a filter function.

like image 36
gelliott181 Avatar answered Nov 09 '22 16:11

gelliott181