2

I have the following object:

var json = {
    "0": (entry.points[0]) ? entry.points[0].points : '-',
    "1": (entry.points[1]) ? entry.points[1].points : '-',
    "2": (entry.points[2]) ? entry.points[2].points : '-',
    "3": (entry.points[3]) ? entry.points[3].points : '-',
    "4": (entry.points[4]) ? entry.points[4].points : '-',
    ...
}

What I want is to build that json in a for loop, and all the numbers will be the index. Is this possible?

2 Answers 2

2

Like this, for example:

var json = {};
for (var i = 0; i < entry.points.length; i++) {
    json[i] = entry.points[i] ? entry.points[i].points : '-';
}
Sign up to request clarification or add additional context in comments.

4 Comments

And then: JSON.stringify(json)
I think that OP want object, json is just unfortunate name.
@dfsq why does json[i] add the keys to the beginning of json? I mean if i had json = { "some": "thing"} the "some" key will be the last one!! how can I push those keys in the loop to the end of the json?
@Egidi There is no beginning or end in this case, this is just how browser renders it. Object doesn't have notion of properties order. If you need ordered properties you need to use array, not an object.
0

Try this:

var json = {};
for(var i=0; i<entry.points.length; i++) {
 json[i] = (entry.points[i]) ? entry.points[i].points : '-'
}

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.