Here is my object literal:
var obj = {key1: value1, key2: value2};
How can I add field key3
with value3
to the ob
You can create a new object by using the {[key]: value}
syntax:
const foo = {
a: 'key',
b: 'value'
}
const bar = {
[foo.a]: foo.b
}
console.log(bar); // {key: 'value'}
console.log(bar.key); // value
const baz = {
['key2']: 'value2'
}
console.log(baz); // {key2: 'value2'}
console.log(baz.key2); // value2
With the previous syntax you can now use the spread syntax {...foo, ...bar}
to add a new object without mutating your old value:
const foo = {a: 1, b: 2};
const bar = {...foo, ...{['c']: 3}};
console.log(bar); // {a: 1, b: 2, c: 3}
console.log(bar.c); // 3