Laziale Laziale - 2 months ago 8
Javascript Question

js trying to access array object gives me undefined

I have this js output

enter image description here

I'm trying to access the first member of the ModelState array using this approach:

console.log(data.ModelState[0]);


But I'm getting undefined error.

Also when trying to do alert(data.ModelState) I'm getting Object object.

Any idea how can I access the first value in the ModelState array? Thanks

Answer

I appears that your data contains an array which has a blank or whitespace key. So it most likely looks like this

{
    ModelState: {
        "": [ "string1", "string2" ]
    }
}

You would need to access it via the key there, as long as you know what it is, for example data.ModelState[""][1] //"string1"

There are also alternatives if you are not sure what they key would be or want a less brittle code:

 var data = {
   ModelState: {
     "": [ "string1", "string2" ]
   }
 };

console.log("--Using Object.keys--")
Object.keys(data.ModelState).forEach(function(key) {
  console.log(data.ModelState[key]);
})

console.log("--Using for...in loop--")
for (var key in data.ModelState) {
  console.log(data.ModelState[key]);
}