2

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?

1
  • 2
    How is that JSON generated? -i.e. where are you viewing it? Commented Jun 8, 2011 at 3:12

1 Answer 1

3

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.

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.