Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a new property at the beginning of a JSON object

I have this JSON:

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

I want to add a new element at the beginning, I want to end up having this:

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

I tried this but it is not working:

myVar.unshift({"5":"Electronics"});

Thanks!

like image 990
lito Avatar asked May 21 '12 19:05

lito


1 Answers

Javascript objects don't have an order associated with them by definition, so this is impossible.

You should use an array of objects if you need an order:

var myArray = [
    {number: '9', value:'Automotive & Industrial'},
    {number: '1', value:'Books'},
    {number: '7', value:'Clothing'}
]

then if you want to insert something in the first position, you can use the unshift method of Arrays.

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'}]

more detail here: Does JavaScript Guarantee Object Property Order?

like image 197
Ryan O'Donnell Avatar answered Oct 20 '22 09:10

Ryan O'Donnell