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?

3
  • 5
    obj['item[]'].length Commented Aug 14, 2016 at 13:25
  • var obj = req.body; if this code is on node server, then are you doing app.use(bodyParser.json()) on node? Commented Aug 14, 2016 at 13:27
  • JSON is a textual notation for data exchange. (More) 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. Commented Aug 14, 2016 at 13:30

1 Answer 1

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);
})

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.