javascript 在 JSON 对象中的特定位置插入属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13496023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:58:22  来源:igfitidea点击:

Inserting property in JSON object at a specific position

javascriptjqueryjson

提问by Chris X

Possible Duplicate:
Does JavaScript Guarantee Object Property Order?

可能的重复:
JavaScript 是否保证对象属性顺序?

I would like to know how I can insert a JSON object property at a specific position? Let's assume this Javascript object:

我想知道如何在特定位置插入 JSON 对象属性?让我们假设这个 Javascript 对象:

var data = {
  0: 'lorem',
  1: 'dolor sit',
  2: 'consectetuer'
}

I have an ID and a string, like:

我有一个 ID 和一个字符串,例如:

var id = 6;
var str = 'adipiscing';

Now, I would like to insert the idbetween 0and 1(for example) and it should be like:

现在,我想插入id之间01(例如),它应该是这样的:

data = {
  0: 'lorem',
  6: 'adipiscing',
  1: 'dolor sit',
  2: 'consectetuer'
}

How can I do this?Is there any jQuery solution for this?

我怎样才能做到这一点?是否有任何 jQuery 解决方案?

回答by Cerbrus

To specify an order in which elements of an object are placed, you'll need to use an array of objects, like this:

要指定对象元素的放置顺序,您需要使用对象数组,如下所示:

data = [
    {0: 'lorem'},
    {1: 'dolor sit'},
    {2: 'consectetuer'}
]

You can then push a element to a certain position in the array:

然后,您可以将元素推送到数组中的某个位置:

// Push {6: 'adipiscing'} to position 1
data.splice(1, 0, {6: 'adipiscing'})

// Result:
data = [
    {0: 'lorem'},
    {6: 'adipiscing'},
    {1: 'dolor sit'},
    {2: 'consectetuer'}
]
// Access it:
data[0][0] //"lorem"

However, this will render the indices you've specified ({0:) pretty much useless.

但是,这会使您指定的 ( {0:)索引变得毫无用处。