在JSON对象的顶部添加内容 [英] Adding something to the top of a JSON object

查看:141
本文介绍了在JSON对象的顶部添加内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON对象,它在页面加载时启动,如下所示:

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

有没有办法在第一个 foo 元素,这样当为数据中的var i执行时,新元素将在启动对象时添加的元素之前循环播放? / p>

原因是,我正在向用户显示一些项目。当用户通过javascript添加新项目时,我希望这个新项目显示在所有现有项目之上,但是当我添加新项目时,即

  data [newItem] = newItem; 

然后JSON对象如下所示:

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

而不是我想要的,这是:

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

任何想法?

解决方案

在JS中,不保证对象属性的顺序。因此,即使它们是在JSON字符串中排序的,当解析为JS对象时,您也永远无法预测它们出现的顺序。



更好地使用数组。您可以使用 unshift()方法将项目放在第一个索引中。

  var data = [bar,bar2,bar3]; 

data.unshift(newItem);

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


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?

解决方案

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];

这篇关于在JSON对象的顶部添加内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆