在JSON的开头添加新元素

lit*_*ito 4 javascript

我有这个JSON:

var myVar = {
     "9":"Automotive & Industrial",
     "1":"Books",
     "7":"Clothing"
};
Run Code Online (Sandbox Code Playgroud)

我想在开头添加一个新元素,我想最终得到这个:

var myVar = {
     "5":"Electronics",
     "9":"Automotive & Industrial",
     "1":"Books",
     "7":"Clothing"
};
Run Code Online (Sandbox Code Playgroud)

我试过这个,但它不起作用:

myVar.unshift({"5":"Electronics"});
Run Code Online (Sandbox Code Playgroud)

谢谢!

Rya*_*ell 10

根据定义,Javascript对象没有与它们关联的顺序,因此这是不可能的.

如果需要订单,则应使用对象数组:

var myArray = [
    {number: '9', value:'Automotive & Industrial'},
    {number: '1', value:'Books'},
    {number: '7', value:'Clothing'}
]
Run Code Online (Sandbox Code Playgroud)

那么如果你想在第一个位置插入一些东西,你可以使用Arrays的unshift方法.

myArray.unshift({number:'5', value:'Electronics'})

//myArray is now the following
[{number:'5', value:'Electronics'},
 {number: '9', value:'Automotive & Industrial'},
 {number: '1', value:'Books'},
 {number: '7', value:'Clothing'}]
Run Code Online (Sandbox Code Playgroud)

更多详细信息: JavaScript保证对象属性订单?


Jon*_*n M 0

只需这样做:

var myVar = {
     "9":"Automotive & Industrial",
     "1":"Books",
     "7":"Clothing"
};

// if you want to add a property, then...

myVar["5"]="Electronics"; // note that it won't be "first" or "last", it's just "5"
Run Code Online (Sandbox Code Playgroud)