2

I appreciate there are a few questions here already about how to identify an array. However, I can't find anything regarding identifying an array within an array of objects.

Given the following array:

var pagesArray = [{
   category: 'pages1',
   pages: [
       'firstPage1',
       'secondPage1',
       'thirdPage1',
       'fourthPage1']
   }
}];

I have tried to loop through and identify that pages is also an array like so:

EDIT

Actually o in the next example should have been pagesArray but I've left it as is so that the answers make sense.

for(var p in o){     
    console.log(typeof p);
    console.log(p instanceof Array)
    console.log(Object.prototype.toString.call(p))                         
}    

The output returned for pages is:

string 
false 
[object String] 

Is there a way to correctly identify that the property is an array or am I misunderstanding something?

davy
  • 4,474
  • 10
  • 48
  • 71

2 Answers2

3

For this answer, I assume your are using a for..in loop to iterate over the properties of the object inside pagesArray, that is, pagesArray[0].

for..in iterates over keys, not values. Keys are always strings, so in your loop, p is always a string (here, "categories", or "values"). To get the value associated with a key, use o[p]. You want to test if o["pages"] is an array, not if the string "pages" is an array.

for(var p in o){
    var value = o[p];

    console.log(typeof value);
    console.log(value instanceof Array)
    console.log(Object.prototype.toString.call(value))                         
}
apsillers
  • 112,806
  • 17
  • 235
  • 239
0

pagesArray[0].pages instanceof Array works fine, though you have an extra curly brace causing a syntax error.

http://jsfiddle.net/vVPCA/

jbabey
  • 45,965
  • 12
  • 71
  • 94