Add new item at the beginning of JSON

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 get the following:

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

I tried this, but it does not work:

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

Thank!

+3
source share
7 answers

Just do this:

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 just "5"
+1
source

Javascript objects do not have an order associated with them by definition, so this is not possible .

You need to 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 for 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 details here: Is the order for the JavaScript property object guaranteed?

+9
source

JSON .

[, ], .

+2

Javascript . , . for-in, . . , , , .

+2

, - , .

, JSON, :

var myNewVar={'5':'Electronics'};
for (xx in myVar) {
    myNewVar[xx]=myVar[xx];
}
+2

, lodash, :

var myObj = _.merge({ col1: 'col 1', col2: 'col 2'}, { col3: 'col 3', col4: 'col 4' });

:

{ col1: 'col 1', col2: 'col 2', col3: 'col 3', col4: 'col 4' }

, , , , . , , . : "merge" , , .

+2

Try something like this:

myObject.sort(function(a,b) { return parseFloat(a.price) - parseFloat(b.price) } );

or

myObject.sort(function(a,b) { return parseFloat(a.get("price")) - parseFloat(b.get("price")) } );
0
source

All Articles