Adding properties to the start of an object in javascript


Javascript has the build in unshift() method for pushing items to the beginning of an array. However unfortunately there is not an equivalent method for objects. One solution is to use arrays instead of objects when possible. However this might not always be possible. There are many times when you get a JSON as a response from an AJAX request and you need to display something before the returned items because of a user action.

push properties to start of object in javascript
The solution is to use a temporary object to load all properties in the right order and then use it to replace the original object. Let’s see it in action in the following example:
var new_object = {}; 
new_object[name] = value; // The property we need at the start 

for (var key in old_object) { // Looping through all values of the old object 
  new_object[key] = old_object[key];
  delete old_object[key]; 
} 

old_object = new_object; // Replacing the old object with the desired one 

Follow us for more great posts in the future.

Facebook Twitter

Get posts in your email

Bibakis.com