Here is some output that I get from firebug

<div id='div_undefined'>[{"Region":"AD","Date":"","ArticleID":"abc-345"},    {"Region":"CD","Date":"","ArticleID":"abc-345"}]</div>

You can see the JS Object array in there and notice the div_undefined. If you look at the funciton below I know that my object is defined because it is printing out. Why would Items[0] return undefined when I try to access ArticleID

here is the code from my function

function myFunc(Items){
    var item = Items[0];
    Write("<div id='div_" + item.ArticleID + "'>" + Items + "</div>");
}
share|improve this question
Why would you debug like this, and not just console.log(item)? – Matt Ball Jan 15 at 23:31
feedback

1 Answer

up vote 5 down vote accepted

If concatenating Items produces this output, then it's a string (containing JSON) and you have to parse it to a JS data structure first (an array in this case):

function myFunc(Items){
    Items = JSON.parse(Items);
    var item = Items[0];
    Write("<div id='div_" + item.ArticleID + "'>" + Items + "</div>");
    // Will output
    // <div id='div_abc-345'>[object Object], [object Object]</div>
}

Ideally you would do this before you pass the value to the function. I don't know which output you are after, so that's all I can advice.


Otherwise, Items[0] refers to the first letter of the string (a string as well) and strings don't have an ArticleID property, hence you get undefined.


You might find this question helpful as well: I have a nested data structure / JSON, how can I access a specific value? And as mentioned by Matt (and in the other question), if you want to debug your code, use console.log.

share|improve this answer
That makes perfect sense as before I send the data via jQuery I do this JSON.stringify(parameterArray) so yep I have a string and not an object. Thanks for pointing that out guys. – user1735894 Jan 16 at 2:07
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.