0

I have an array set like tempArray[i] = {Name: 'foo', Data: 'bar'}
How would you use indexOf to search through tempArray looking to see if the name element was present? I.e

if(tempArray.indexOf('foo') > -1)
{
 //do stuff
}

Ive tried this way but it never seems to be true because I think 'foo' is not accessible due to it being reference by the .Name

Mike Laren
  • 8,028
  • 17
  • 51
  • 70
Dennington-bear
  • 1,732
  • 4
  • 18
  • 44

3 Answers3

1

Why not just check for the property?

tempArray[i] = {Name: 'foo', Data: 'bar'}

if(tempArray[i].name)
{
 //do stuff
}
joshvito
  • 1,498
  • 18
  • 23
  • If `name` is falsy (evaluates to `false` like `0`, `false`, `null`) then it would also fail, despite existing. – Matt Apr 10 '15 at 15:36
0

Assuming you want to search through the array for an object with Name property:

//this assumes tempArray has objects only!
for(var i = 0, len = tempArray.length; i< len; i++){
  if(tempArray[i].hasOwnProperty('Name')) {

    //do stuff
  }
}
Bwaxxlo
  • 1,860
  • 13
  • 18
0

That is an object, and you can do this to check that the Name property is present:

for (var i = 0; i < tempArray.length; i++)
{
    if (Object.keys(tempArray[i]).indexOf('Name') >= 0)
    {
        // do soemthing
    }
}
Matt
  • 1,377
  • 2
  • 13
  • 26