Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

javascript - Adding something to the top of a JSON object

I have a JSON object which is initiated when the page is loaded, like this:

data[foo] = bar;
data[foo2] = bar2;
data[foo3] = bar3;

Is there a way to inject an element before the first foo element, so that when doing a for var i in data, the new element will be looped through before the elements that were added when the object was initiated?

The reason is, I'm displaying some items to the user. When the user adds a new item via javascript, I want this new item to be displayed above all the existing items, however when I add the new item, i.e

data[newItem] = newItem;

Then the JSON object looks like this:

data[foo] = bar;
data[foo2] = bar2;
data[foo3] = bar3;
data[newItem] = newItem;

Instead of how I want, which is:

data[newItem] = newItem;
data[foo] = bar;
data[foo2] = bar2;
data[foo3] = bar3;

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In JS, object properties' order is not guaranteed. Therefore, even if they are ordered in the JSON string, when parsed as a JS object, you will never predict in what order they come up.

Better use arrays instead. You could use the unshift() method to put the item in the first index.

var data = [bar,bar2,bar3];

data.unshift(newItem);

//data = [newItem,bar,bar2,bar3];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...