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?

4
  • have you tried 'length'? Commented Aug 12, 2013 at 14:36
  • SyntaxError: Unexpected token } on your "array" Commented Aug 12, 2013 at 14:36
  • 1
    It's not clear what o is. Commented Aug 12, 2013 at 14:37
  • your answer is here : stackoverflow.com/questions/4775722/… Commented Aug 12, 2013 at 14:39

2 Answers 2

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))                         
}
Sign up to request clarification or add additional context in comments.

1 Comment

Bingo. This is a common mistake in javascript.
0

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

http://jsfiddle.net/vVPCA/

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.