How to add a property at the beginning of an object in javascript
The simplest way is to use the spread operator.
let obj = {'b': 2, 'c': 3};
let newObj = {'a': 1, ...obj};
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 :)
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 });