Zaki Zaki - 1 year ago 39
Javascript Question

Add Dynamic Property To End of Object

I am creating an object and set its properties dynamically and push it to an array, as below:

var modelData = [];
var data = {}
data['rain'] = '123';
var items = [{name: 'prod', default_id: 1}, {name: 'dev', default_id: 2}]
for (var i = 0; i < items.length; i++) {
var id = items[i].name;
data[id] = items[i].default_id;

This works fine but by default it adds the properties in ascending order. I want it to be added to the end of the object, so my properties would be
rain, prod, dev
instead of
dev, prod, rain

Is that possible?

see this jsfiddle console for an example.


Objects don't have a guaranteed order in JS. The closest thing you can get is an array of arrays:

var ordered_object = [];
ordered_object.push(['rain', 'First element']);
ordered_object.push(['prod', 'Second element']);
ordered_object.push(['dev', 'Third element']);
ordered_object.forEach(function(pair) {
    var key = pair[0],
        value = pair[1];

    console.log(key + ': ' + value);

It will be ordered, but getting the value of a "property" (they're not really properties any more) is a little more difficult:

function get_value(ordered_object, key) {
    for (var i = 0; i < ordered_object.length; i++) {
        if (ordered_object[i][0] === key) {
            return ordered_object[i][1];