如何将键/值对添加到JavaScript对象?

JavaScript

2020-03-09

这是我的对象文字:

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

我如何添加字段key3value3对象?

第276篇《如何将键/值对添加到JavaScript对象?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

9个回答
蛋蛋蛋蛋 2020.03.09
arr.push({key3: value3});
蛋蛋GO 2020.03.09

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);
}
逆天前端宝儿 2020.03.09

According to Property Accessors defined in ECMA-262(http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf, P67), there are two ways you can do to add properties to a exists object. All these two way, the Javascript engine will treat them the same.

The first way is to use dot notation:

obj.key3 = value3;

But this way, you should use a IdentifierName after dot notation.

The second way is to use bracket notation:

obj["key3"] = value3;

and another form:

var key3 = "key3";
obj[key3] = value3;

This way, you could use a Expression (include IdentifierName) in the bracket notation.

猴子Davaid老丝 2020.03.09

supported by most of browsers, and it checks if object key available or not you want to add, if available it overides existing key value and it not available it add key with value

example 1

let my_object = {};

// now i want to add something in it  

my_object.red = "this is red color";

// { red : "this is red color"}

example 2

let my_object = { inside_object : { car : "maruti" }}

// now i want to add something inside object of my object 

my_object.inside_object.plane = "JetKing";

// { inside_object : { car : "maruti" , plane : "JetKing"} }

example 3

let my_object = { inside_object : { name : "abhishek" }}

// now i want to add something inside object with new keys birth , gender 

my_object.inside_object.birth = "8 Aug";
my_object.inside_object.gender = "Male";


    // { inside_object : 
//             { name : "abhishek",
//               birth : "8 Aug",
//               gender : "Male" 
//            }   
//       }
null 2020.03.09

Your example shows an Object, not an Array. In that case, the preferred way to add a field to an Object is to just assign to it, like so:

arr.key3 = value3;
StafanHarry 2020.03.09
arr.key3 = value3;

因为您的arr并不是一个数组,而是一个原型对象。真正的数组是:

var arr = [{key1: value1}, {key2: value2}];

但是还是不对 实际上应该是:

var arr = [{key: key1, value: value1}, {key: key2, value: value2}];
Harry小宇宙 2020.03.09

我知道已经有一个可以接受的答案,但是我想我已经在某个地方记录了我的想法。请[人们]随意戳破这个想法,因为我不确定这是否是最佳解决方案...但是我只是在几分钟前将其汇总:

Object.prototype.push = function( key, value ){
   this[ key ] = value;
   return this;
}

您将以这种方式利用它:

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

由于原型函数正在返回,因此this您可以继续将的链链接.pushobj变量的末尾obj.push(...).push(...).push(...);

另一个功能是,您可以传递一个数组或另一个对象作为push函数参数中的值。请参阅我的小提琴以获取工作示例:http : //jsfiddle.net/7tEme/

LNear 2020.03.09

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!

蛋蛋Near 2020.03.09

有两种向对象添加新属性的方法

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

使用点表示法:

obj.key3 = "value3";

Using square bracket notation:

obj["key3"] = "value3";

The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example:

var getProperty = function (propertyName) {
    return obj[propertyName];
};

getProperty("key1");
getProperty("key2");
getProperty("key3");

A real JavaScript array can be constructed using either:

The Array literal notation:

var arr = [];

The Array constructor notation:

var arr = new Array();

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android