javascript - How to make a simple json array with push - Stack Overflow

If I have a blog post and I push ments with the line:blogpostments.push({ username: "fred", m

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

blogpostments.push({ username: "fred", ment: "Great"});

the ments section of JSON looks like this:

"ments":[{"0":{"username":"jim","ment":"Good",},"1":{"username":"fred","ment":"great"}}]

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

"ments":[{"username":"jim","ment":"Good"},{"username":"fred","ment":"great"}]

What do I need to change to get this?

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

blogpost.ments.push({ username: "fred", ment: "Great"});

the ments section of JSON looks like this:

"ments":[{"0":{"username":"jim","ment":"Good",},"1":{"username":"fred","ment":"great"}}]

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

"ments":[{"username":"jim","ment":"Good"},{"username":"fred","ment":"great"}]

What do I need to change to get this?

Share Improve this question edited Jun 8, 2011 at 8:31 tooba asked Jun 7, 2011 at 18:27 toobatooba 5695 silver badges23 bronze badges 1
  • 2 How is that JSON generated? -i.e. where are you viewing it? – David Tang Commented Jun 8, 2011 at 3:12
Add a ment  | 

1 Answer 1

Reset to default 3

Wait, is blogpost.ments 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.ments, with this value:

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

and you execute:

blogpost.ments.push({ username: "fred", ment: "Great"});

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

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

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745292163a4620925.html

相关推荐

  • javascript - How to make a simple json array with push - Stack Overflow

    If I have a blog post and I push ments with the line:blogpostments.push({ username: "fred", m

    9小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信