0

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>");
}
user1735894
  • 323
  • 4
  • 16

1 Answers1

6

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: Access / process (nested) objects, arrays or JSON And as mentioned by Matt (and in the other question), if you want to debug your code, use console.log.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    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 '13 at 02:07