Adam Adam - 3 months ago 11
Javascript Question

Fetching index of array inside JSON object on javascript

I am trying to fetch the values of the numbers inside an array of a JSON object.

Here is how the JSON object looks like

{
"item[]": [
"1",
"2",
"3",
"4",
"5",
"6",
"8",
"7",
"9",
"10",
"11",
"12"
]
}


This object comes from a jquery serialize. I have tried,

var obj = req.body;
obj.length //Returns undefined

obj.item ///Return undefined

obj.item[] //Program crashes


I need to access the value so I can make it look something like:

Index 1 = 1
Index 2 = 2
Index 3 = 3 //And so on


How can I achieve this through looping in javascript?

Answer

You should use bracket notation obj['item[]'] instead of dot notation and then you can use forEach loop to get each element of array.

var obj = {"item[]":["1","2","3","4","5","6","8","7","9","10","11","12"]}

obj['item[]'].forEach(function(e, i) {
  console.log('Index ' + i + ' = ' + e);
})

Comments