Adding something to the top of a JSON object

I have a JSON object that starts when the page loads, for example:

data[foo] = bar; data[foo2] = bar2; data[foo3] = bar3; 

Is there a way to insert an element before the first element of foo , so that when for var i in data is executed, the new element will loop to the elements that were added when the object started?

The reason is because I show some elements to the user. When the user adds a new element through javascript, I want this new element to appear above all existing elements, however, when I add a new element, for example,

 data[newItem] = newItem; 

Then the JSON object looks like this:

 data[foo] = bar; data[foo2] = bar2; data[foo3] = bar3; data[newItem] = newItem; 

Instead what I want is:

 data[newItem] = newItem; data[foo] = bar; data[foo2] = bar2; data[foo3] = bar3; 

Any ideas?

+7
source share
6 answers

In JS, the order of object objects is not guaranteed. Therefore, even if they are ordered in a JSON string when parsed as a JS object, you will never predict in which order they appear.

Instead, it is better to use arrays. You can use the unshift() method to place an element in the first index.

 var data = [bar,bar2,bar3]; data.unshift(newItem); //data = [newItem,bar,bar2,bar3]; 
+13
source

As a compliment to Joseph Dreamer answer , I checked some quick checks in firefox and chrome.

Firefox:

 var obj = {}; obj.a = 'a'; obj.c = 'c'; obj.b = 'b'; obj['0'] = '0'; for(var i in obj){ console.log(i); } //prints: a c b 0 

Chrome:

 var obj = {}; obj.a = 'a'; obj.c = 'c'; obj.b = 'b'; obj['0'] = '0'; for(var i in obj){ console.log(i); } //prints: 0 a c b 
+8
source

Is there a way to insert an element before the first foo element?

What comes first in the array:

window.object or window.alert?

Neither of these objects have order. If you want the array to use an array. Objects are not arrays.

If you want to

 var ThingsInOrder = [ FirstThing, SecondThing, ThirdThing ]; ThingsInOrder.push(ForthThing); 

Use an array.

If you want to:

 var ThingsNeverInOrder = { Window, Alert, Derp, Herp }; ThingsNeverInOrder.foo = bar; 

Use object.

+3
source

I came across this and achieved this using:

const newObject = Object.assign({first: value}, oldObject)

As already mentioned, the order is not guaranteed, but for me it is good enough. :)

+2
source

Instead of adding a new value to the same object, you can create a new object and arrange the order of properties as you like. Example:

 var objj1 = {name:'viru',lastname:'nehra'}; 

So, create a new object with the new property you want on top:

 var obj2 = {age: 21} 

and mileage:

 for(var key in objj1){ obj2[key] = objj1[key] } obj2 = {age: 21, name: "viru", lastname: "nehra"} 
0
source

I think you can convert it to a string, add your data at the beginning of the string, and then convert the string to json using "eval"

-3
source

All Articles