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?
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.
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.
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.
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}
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With