cedivad cedivad - 2 months ago 7
Javascript Question

How to add a property at the beginning of an object in javascript

I have

var obj = {'b': 2, 'c': 3};


And i would like to add a property at the beginning (not at the end) of that object:

var obj = {'a': 1, 'b': 2, 'c': 3};


Is there a clean way to do that?

Answer

JavaScript objects are unordered. There is no beginning or end. If you want order, use an array.

var arr = [
    { key: 'b', value: 2 },
    { key: 'c', value: 3 }
];

You can then add to the front of it with unshift:

arr.unshift({ key: 'a', value: 1 });