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
You can either add it this way:
arr['key3'] = value3;
or this way:
arr.key3 = value3;
The answers suggesting keying into the object with the variable key3
would only work if the value of key3
was 'key3'
.
In order to prepend a key-value pair to an object so the for in works with that element first do this:
var nwrow = {'newkey': 'value' };
for(var column in row){
nwrow[column] = row[column];
}
row = nwrow;
We can do this in this way too.
var myMap = new Map();
myMap.set(0, 'my value1');
myMap.set(1, 'my value2');
for (var [key, value] of myMap) {
console.log(key + ' = ' + value);
}
Object.assign()
Object.assign(dest, src1, src2, ...) merges objects.
It overwrites dest
with properties and values of (however many) source objects, then returns dest
.
The
Object.assign()
method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
var obj = {key1: "value1", key2: "value2"};
Object.assign(obj, {key3: "value3"});
document.body.innerHTML = JSON.stringify(obj);
{...}
obj = {...obj, ...pair};
From MDN:
It copies own enumerable properties from a provided object onto a new object.
Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().
Note that Object.assign() triggers setters whereas spread syntax doesn’t.
It works in current Chrome and current Firefox. They say it doesn’t work in current Edge.
var obj = {key1: "value1", key2: "value2"};
var pair = {key3: "value3"};
obj = {...obj, ...pair};
document.body.innerHTML = JSON.stringify(obj);
Object assignment operator +=
:
obj += {key3: "value3"};
Oops... I got carried away. Smuggling information from the future is illegal. Duly obscured!
In case you have multiple anonymous Object literals inside an Object and want to add another Object containing key/value pairs, do this:
Firebug' the Object:
console.log(Comicbook);
returns:
[Object { name="Spiderman", value="11"}, Object { name="Marsipulami", value="18"}, Object { name="Garfield", value="2"}]
Code:
if (typeof Comicbook[3]=='undefined') {
private_formArray[3] = new Object();
private_formArray[3]["name"] = "Peanuts";
private_formArray[3]["value"] = "12";
}
will add Object {name="Peanuts", value="12"}
to the Comicbook Object