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!
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With