Skip to content Skip to sidebar Skip to footer

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 t

Solution 1:

You can also use Object.assign() in ES6 (ES2015+).

let obj = {'b': 2, 'c': 3};
const returnedTarget = Object.assign({a: 1}, obj);

// Object {a: 1, b: 2, c: 3}

Solution 2:

These days you could use the cool spread operator (...) in ES6 (ES2015+), try out the following:

const obj = {'b': 2, 'c': 3};
   
const startAdded = {'a':1 , ...obj};
console.log(startAdded);

const endAdded = {...obj, 'd':4};
console.log(endAdded);

Might help someone out there in the wild :)

Solution 3:

The simplest way is to use the spread operator.

let obj = {'b': 2, 'c': 3};
let newObj = {'a': 1, ...obj};

Solution 4:

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

vararr= [
    { 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 });

Solution 5:

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.

Post a Comment for "How To Add A Property At The Beginning Of An Object In Javascript"