How can I add a key/value pair to a JavaScript obj

2018-12-31 01:57发布

Here is my object literal:

var obj = {key1: value1, key2: value2};

How can I add {key3: value3} to the object?

23条回答
何处买醉
2楼-- · 2018-12-31 02:54

Year 2017 answer: 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.

Live example

var obj = {key1: "value1", key2: "value2"};
Object.assign(obj, {key3: "value3"});

document.body.innerHTML = JSON.stringify(obj);

Year 2018 answer: object spread operator {...}

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.

Live example

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

Year 2019 answer

Object assignment operator +=:

obj += {key3: "value3"};

Oops... I got carried away. Smuggling information from the future is illegal. Duly obscured!

查看更多
临风纵饮
3楼-- · 2018-12-31 02:54

A short and elegant way in next Javascript specification (candidate stage 3) is:

obj = { ... obj, ... { key3 : value3 } }

A deeper discussion can be found in Object spread vs Object.assign and on Dr. Axel Rauschmayers site.

It works already in node.js since release 8.6.0.

Vivaldi, Chrome, Opera, and Firefox in up to date releases know this feature also, but Mirosoft don't until today, neither in Internet Explorer nor in Edge.

查看更多
旧人旧事旧时光
4楼-- · 2018-12-31 02:56
arr.push({key3: value3});
查看更多
看风景的人
5楼-- · 2018-12-31 02:57
var employees = []; 
employees.push({id:100,name:'Yashwant',age:30});
employees.push({id:200,name:'Mahesh',age:35});
查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 02:58

Since its a question of the past but the problem of present. Would suggest one more solution: Just pass the key and values to the function and you will get a map object.

var map = {};
function addValueToMap(key, value) {
map[key] = map[key] || [];
map[key].push(value);
}
查看更多
登录 后发表回答