0

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?

Adam
  • 13
  • 2
  • 5
    `obj['item[]'].length` – Jose Hermosilla Rodrigo Aug 14 '16 at 13:25
  • `var obj = req.body;` if this code is on node server, then are you doing `app.use(bodyParser.json())` on node? – Praveen Prasad Aug 14 '16 at 13:27
  • JSON is a *textual notation* for data exchange. [(More)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. If you *are* dealing with a string, use `JSON.parse` ot parse it, at which point you're not dealing with a string anymore. But given that `obj.length` is undefined, it sounds like you're not dealing with a string. – T.J. Crowder Aug 14 '16 at 13:30

1 Answers1

4

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);
})
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176