tooba
tooba

Reputation: 569

How to make a simple json array with push

If I have a blog post and I push comments with the line:

blogpost.comments.push({ username: "fred", comment: "Great"});

the comments section of JSON looks like this:

"comments":[{"0":{"username":"jim","comment":"Good",},"1":{"username":"fred","comment":"great"}}]

Ideally I'd like to see the JSON without the numerical additions ("0","1", etc) and flatter. Something like:

"comments":[{"username":"jim","comment":"Good"},{"username":"fred","comment":"great"}]

What do I need to change to get this?

Upvotes: 2

Views: 9074

Answers (1)

mgiuca
mgiuca

Reputation: 21357

Wait, is blogpost.comments a JavaScript array, or something else? If it were a JavaScript array, I don't see how executing the first line of code would update the JSON object as you described. I would expect it to automatically do what you expect, which is to push a new item on the end of the array.

In general, if you have an array blogpost.comments, with this value:

[{"username":"jim","comment":"Good"}]

and you execute:

blogpost.comments.push({ username: "fred", comment: "Great"});

You will most certainly end up with blogpost.comments having the value:

[{"username":"jim","comment":"Good"}, { "username": "fred", "comment": "Great"}]

Which leads me to believe that blogpost.comments is not actually an array, but something else. You should give the code for blogpost.comments.push if it is your own code.

So, basically ... make it an array, and it will work as you expect.

Upvotes: 3

Related Questions