Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 949
cedivad Avatar asked Oct 18 '13 19:10

cedivad


People also ask

How do you add properties to an object?

One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.

How do you conditionally add property to an object?

To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.

How properties are assigned to an object in JavaScript?

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.


2 Answers

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} 
like image 180
Justin Avatar answered Sep 23 '22 11:09

Justin


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 :)

like image 42
darmis Avatar answered Sep 23 '22 11:09

darmis