5

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!

jbabey
  • 42,963
  • 11
  • 66
  • 94
lito
  • 2,792
  • 9
  • 40
  • 68
  • 1
    unshift is for arrays `myVar` is not an array – Musa May 21 '12 at 19:33
  • 2
    An object is an unordered list of key-value-pairs so there is no "beginning" or "end" – Andreas May 21 '12 at 19:33
  • 3
    This is not JSON. JSON is a string. This is just regular ol' javascript code for an object literal. – Jonathan M May 21 '12 at 19:34
  • 1
    Check out the following SO question for detail on Objects vs Arrays in javascript, and their various use cases. http://stackoverflow.com/questions/688097/objects-vs-arrays-in-javascript-for-key-value-pairs It seems to me that you just want a nested object with an ID field, perhaps. – dwerner May 21 '12 at 19:35

8 Answers8

12

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?

Community
  • 1
  • 1
Ryan O'Donnell
  • 461
  • 2
  • 10
2

There is no way to add new entries to JSON and control the position of them.

If you want to deal with order [strange since objects are unordered], you would have to basically create a new object and append the data.

epascarello
  • 185,306
  • 18
  • 175
  • 214
2

Javascript object properties are not deterministically ordered. Properties are accessible no matter what order they're in. If you are depending on them to be in a specific order for a for-in loop, I would suggest rethinking your strategy. Different browsers will take different approaches to ordering the properties. While many browsers will in fact process them in the order you created them, that behavior isn't actually defined in the language spec so you cannot rely on it.

Michael Berkowski
  • 253,311
  • 39
  • 421
  • 371
2

I think the unshift issue might come from the fact that you an associative array. Definition of associative array

This might be a hack but if you MUST have that value at the start of the JSON object, how about:

var myNewVar={'5':'Electronics'};
for (xx in myVar) {
    myNewVar[xx]=myVar[xx];
}
E. Maggini
  • 7,228
  • 5
  • 23
  • 36
2

This Can be done using the lodash merge function like so:

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

Your final object will look like this:

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

As others mentioned, there is no guarantee that the order of the keys in the object will remain the same, depending on what you do with it. But, if you perform the merge as your final step, you should be ok. Note, the 'merge' function will produce a completely new object, it will not alter either of the objects you pass into it.

bbeny
  • 592
  • 1
  • 6
  • 17
1

Just do it this way:

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"
Jonathan M
  • 16,131
  • 8
  • 49
  • 88
  • `myVar.5="Electronics";` would cause a syntax error, you'll have to do it like `myVar.["5"]="Electronics";` – Musa May 21 '12 at 19:41
0

Try something like that:

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")) } );
Himanshu Jansari
  • 28,446
  • 26
  • 101
  • 128
Valeriane
  • 768
  • 2
  • 13
  • 35
0

stringify and modify

var foo = {a:1,b:2,c:3};
var bar = JSON.stringify(foo);
foo = JSON.parse('{"d":4,' + bar.slice(1));
alert(JSON.stringify(foo));