最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论