Here is my object literal:
这是我的对象文字:
var obj = {key1: value1, key2: value2};
How can I add {key3: value3}
to the object?
如何向对象添加{key3: value3} ?
21 个解决方案
#1
1621
There are two ways to add new properties to an object:
向对象添加新属性有两种方法:
var obj = {
key1: value1,
key2: value2
};
Using dot notation:
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:
一个真正的JavaScript数组也可以使用:
The Array literal notation:
var arr = [];
The Array constructor notation:
var arr = new Array();
#2
74
I have grown fond of the LoDash / Underscore when writing larger projects.
我开始喜欢在写大项目时使用破折号/下划线。
Adding by obj['key']
or obj.key
are all solid pure JavaScript answers. However both of LoDash and Underscore libraries do provide many additional convenient functions when working with Objects and Arrays in general.
添加obj['key']或obj。键都是纯JavaScript的可靠答案。然而,在处理对象和数组时,LoDash和下划线库都提供了许多额外的方便函数。
.push()
is for Arrays, not for objects.
push()用于数组,而不是对象。
Depending what you are looking for, there are two specific functions that may be nice to utilize and give functionality similar to the the feel of arr.push()
. For more info check the docs, they have some great examples there.
根据您正在寻找的内容,有两个特定的函数可以很好地利用,并提供与arr.push()类似的功能。要了解更多信息,请查看文档,那里有一些很好的例子。
_.merge (Lodash only)
The second object will overwrite or add to the base object. undefined
values are not copied.
第二个对象将覆盖或添加到基本对象。未定义的值不会被复制。
var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
_.merge(obj, obj2);
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3"}
_.extend / _.assign
The second object will overwrite or add to the base object. undefined
will be copied.
第二个对象将覆盖或添加到基本对象。未定义将被复制。
var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
_.extend(obj, obj2);
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3", key4: undefined}
_.defaults
The second object contains defaults that will be added to base object if they don't exist. undefined
values will be copied if key already exists.
第二个对象包含将被添加到基对象的默认值,如果它们不存在的话。如果键已经存在,则将复制未定义的值。
var obj = {key3: "value3", key5: "value5"};
var obj2 = {key1: "value1", key2:"value2", key3: "valueDefault", key4: "valueDefault", key5: undefined};
_.defaults(obj, obj2);
console.log(obj);
// → {key3: "value3", key5: "value5", key1: "value1", key2: "value2", key4: "valueDefault"}
$.extend
In addition, it may be worthwhile mentioning jQuery.extend, it functions similar to _.merge and may be a better option if you already are using jQuery.
此外,值得一提的是jQuery。扩展,它的功能类似于_。合并,如果您已经在使用jQuery,这可能是一个更好的选择。
The second object will overwrite or add to the base object. undefined
values are not copied.
第二个对象将覆盖或添加到基本对象。未定义的值不会被复制。
var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
$.extend(obj, obj2);
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3"}
Object.assign()
It may be worth mentioning the ES6/ ES2015 Object.assign, it functions similar to _.merge and may be the best option if you already are using an ES6/ES2015 polyfill like Babel if you want to polyfill yourself.
值得一提的是ES6/ ES2015对象。赋值,它的函数类似于_。合并,如果你已经在使用ES6/ES2015的polyfill,比如Babel,如果你想自己进行polyfill的话,这可能是最好的选择。
The second object will overwrite or add to the base object. undefined
will be copied.
第二个对象将覆盖或添加到基本对象。未定义将被复制。
var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
Object.assign(obj, obj2);
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3", key4: undefined}
#3
69
Year 2017 answer: Object.assign()
Object.assign(dest, src1, src2, ...) merges objects.
对象。赋值(dest, src1, src2,…)合并对象。
It overwrites dest
with properties and values of (however many) source objects, then returns dest
.
它使用源对象(无论多少)的属性和值覆盖dest,然后返回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.assign()方法用于将所有可枚举的自身属性值从一个或多个源对象复制到目标对象。它将返回目标对象。
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()
.使用比Object.assign()更短的语法可以进行浅克隆(不包括原型)或对象合并。
Note that
Object.assign()
triggers setters whereas spread syntax doesn’t.注意Object.assign()触发器设置,而spread语法没有。
Live example
It works in current Chrome and current Firefox. They say it doesn’t work in current Edge.
它可以在当前的Chrome和Firefox中工作。他们说它在当前的边缘上不起作用。
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!
哎呀……我带走了。从未来走私信息是非法的。适时地掩盖!
#4
62
You could use either of these (provided key3 is the acutal key you want to use)
您可以使用其中任何一个(假设key3是您想要使用的acutal键)
arr[ 'key3' ] = value3;
or
或
arr.key3 = value3;
If key3 is a variable, then you should do:
如果key3是一个变量,那么您应该:
var key3 = 'a_key';
var value3 = 3;
arr[ key3 ] = value3;
After this, requesting arr.a_key
would return the value of value3
, a literal 3
.
在这之后,请求加勒比海盗。a_key将返回value3的值,一个文本3。
#5
26
arr.key3 = value3;
because your arr is not really an array... It's a prototype object. The real array would be:
因为arr不是一个数组…这是一个原型对象。真正的数组是:
var arr = [{key1: value1}, {key2: value2}];
but it's still not right. It should actually be:
但这还是不对的。它实际上应该:
var arr = [{key: key1, value: value1}, {key: key2, value: value2}];
#6
22
var employees = [];
employees.push({id:100,name:'Yashwant',age:30});
employees.push({id:200,name:'Mahesh',age:35});
#7
8
I know there is already an accepted answer for this but I thought I'd document my idea somewhere. Please [people] feel free to poke holes in this idea, as I'm not sure if it is the best solution... but I just put this together a few minutes ago:
我知道这个问题已经有了一个公认的答案,但我想我应该把我的想法记录下来。请[人们]随意在这个想法上戳洞,因为我不确定这是否是最好的解决办法……但我只是在几分钟前把这些放在一起:
Object.prototype.push = function( key, value ){
this[ key ] = value;
return this;
}
You would utilize it in this way:
你可以这样利用它:
var obj = {key1: value1, key2: value2};
obj.push( "key3", "value3" );
Since, the prototype function is returning this
you can continue to chain .push
's to the end of your obj
variable: obj.push(...).push(...).push(...);
由于原型函数正在返回这个,所以您可以继续链式。push's到obj变量的末尾:object .push(…).push(…).push(…).push(…).push(…);
Another feature is that you can pass an array or another object as the value in the push function arguments. See my fiddle for a working example: http://jsfiddle.net/7tEme/
另一个特性是,您可以将数组或其他对象作为push函数参数中的值传递。请参阅我的小提琴的工作示例:http://jsfiddle.net/7tEme/。
#8
8
You can create a class with the answer of @Ionuț G. Stan
您可以创建一个类与@Ionuțg·斯坦的答案
function obj(){
obj=new Object();
this.add=function(key,value){
obj[""+key+""]=value;
}
this.obj=obj
}
Creating a new object with the last class:
使用最后一个类创建一个新对象:
my_obj=new obj();
my_obj.add('key1', 'value1');
my_obj.add('key2', 'value2');
my_obj.add('key3','value3');
Printing the object
打印对象
console.log(my_obj.obj) // Return {key1: "value1", key2: "value2", key3: "value3"}
Printing a Key
打印一个关键
console.log(my_obj.obj["key3"]) //Return value3
I'm newbie in javascript, comments are welcome. Works for me.
我是javascript新手,欢迎评论。为我工作。
#9
6
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;
#10
6
Two most used ways already mentioned in most answers
在大多数答案中已经提到了两种最常用的方法
obj.key3 = "value3";
obj["key3"] = "value3";
One more way to define a property is using Object.defineProperty()
定义属性的另一种方法是使用Object.defineProperty()
Object.defineProperty(obj, 'key3', {
value: "value3", // undefined by default
enumerable: true, // false by default
configurable: true, // false by default
writable: true // false by default
});
This method is useful when you want to have more control while defining property. Property defined can be set as enumerable, configurable and writable by user.
当您想在定义属性时拥有更多的控件时,此方法是有用的。定义的属性可以设置为可枚举、可配置和用户可写。
#11
5
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:
Firebug的对象:
console.log(Comicbook);
returns:
返回:
[Object { name="Spiderman", value="11"}, Object { name="Marsipulami", value="18"}, Object { name="Garfield", value="2"}]
[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
在Comicbook对象中添加Object {name="Peanuts", value="12"}。
#12
5
Either obj['key3'] = value3
or obj.key3 = value3
will add the new pair to the obj
.
obj['key3'] = value3或obj。key3 = value3将向obj添加新对。
However, I know jQuery was not mentioned, but if you're using it, you can add the object through $.extend(obj,{key3: 'value3'})
. E.g.:
但是,我知道jQuery没有被提及,但是如果您使用它,您可以通过$添加对象。扩展(obj,{ key3:‘value3 })。例如:
var obj = {key1: 'value1', key2: 'value2'};
$('#ini').append(JSON.stringify(obj));
$.extend(obj,{key3: 'value3'});
$('#ext').append(JSON.stringify(obj));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="ini">Initial: </p>
<p id="ext">Extended: </p>
jQuery.extend(target[,object1][,objectN]) merges the contents of two or more objects together into the first object.
扩展(target[,object1][,objectN])将两个或多个对象的内容合并到第一个对象中。
And it also allows recursive adds/modifications with $.extend(true,object1,object2);
:
它还允许使用$.extend进行递归添加/修改(true,object1,object2);
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};
$("#ini").append(JSON.stringify(object1));
$.extend( true, object1, object2 );
$("#ext").append(JSON.stringify(object1));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="ini">Initial: </p>
<p id="ext">Extended: </p>
#13
4
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'
.
只有当key3的值为“key3”时,才会出现使用key3对对象进行键控的答案。
#14
4
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.
根据ECMA-262中定义的属性访问器(http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf, P67),有两种方法可以将属性添加到现有对象中。所有这两种方式,Javascript引擎都会对它们进行相同的处理。
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.
这样,您可以在方括号符号中使用表达式(包括IdentifierName)。
#15
3
A short and elegant way in next Javascript specification (candidate stage 3) is:
下一个Javascript规范(候选阶段3)中一个简短而优雅的方法是:
obj = { ... obj, ... { key3 : value3 } }
obj = {…obj,……{key3: value3}
A deeper discussion can be found in Object spread vs Object.assign and on Dr. Axel Rauschmayers site.
对对象展开与对象展开有更深层次的探讨。分配并在Axel Rauschmayers博士的网站上。
It works already in node.js since release 8.6.0.
它已经在node中工作了。自发布8.6.0 js。
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.
Vivaldi, Chrome, Opera和Firefox的最新版本也知道这个功能,但是Mirosoft直到今天才知道,无论是在ie还是Edge中。
#16
3
var arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];
var injectObj = {isActive:true, timestamp:new Date()};
// function to inject key values in all object of json array
function injectKeyValueInArray (array, keyValues){
return new Promise((resolve, reject) => {
if (!array.length)
return resolve(array);
array.forEach((object) => {
for (let key in keyValues) {
object[key] = keyValues[key]
}
});
resolve(array);
})
};
//call function to inject json key value in all array object
injectKeyValueInArray(arrOfObj,injectObj).then((newArrOfObj)=>{
console.log(newArrOfObj);
});
Output like this:-
输出:-
[ { name: 'eve',
isActive: true,
timestamp: 2017-12-16T16:03:53.083Z },
{ name: 'john',
isActive: true,
timestamp: 2017-12-16T16:03:53.083Z },
{ name: 'jane',
isActive: true,
timestamp: 2017-12-16T16:03:53.083Z } ]
#17
2
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);
}
#18
0
In order to prepend a key-value pair to an object so the for in works with that element first do this:
为了将键-值对前置到一个对象,for In与该元素一起工作,首先要做的是:
var nwrow = {'newkey': 'value' };
for(var column in row){
nwrow[column] = row[column];
}
row = nwrow;
#19
0
Best way to achieve same is stated below:
达到这一目标的最佳方法如下:
function getKey(key) {
return `${key}`;
}
var obj = {key1: "value1", key2: "value2", [getKey('key3')]: "value3"};
//console.log(obj);
#20
0
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.
因为这是过去的问题,而不是现在的问题。还有一个解决方案:将键和值传递给函数,就会得到一个map对象。
var map = {};
function addValueToMap(key, value) {
map[key] = map[key] || [];
map[key].push(value);
}
#21
-16
arr.push({key3: value3});
#1
1621
There are two ways to add new properties to an object:
向对象添加新属性有两种方法:
var obj = {
key1: value1,
key2: value2
};
Using dot notation:
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:
一个真正的JavaScript数组也可以使用:
The Array literal notation:
var arr = [];
The Array constructor notation:
var arr = new Array();
#2
74
I have grown fond of the LoDash / Underscore when writing larger projects.
我开始喜欢在写大项目时使用破折号/下划线。
Adding by obj['key']
or obj.key
are all solid pure JavaScript answers. However both of LoDash and Underscore libraries do provide many additional convenient functions when working with Objects and Arrays in general.
添加obj['key']或obj。键都是纯JavaScript的可靠答案。然而,在处理对象和数组时,LoDash和下划线库都提供了许多额外的方便函数。
.push()
is for Arrays, not for objects.
push()用于数组,而不是对象。
Depending what you are looking for, there are two specific functions that may be nice to utilize and give functionality similar to the the feel of arr.push()
. For more info check the docs, they have some great examples there.
根据您正在寻找的内容,有两个特定的函数可以很好地利用,并提供与arr.push()类似的功能。要了解更多信息,请查看文档,那里有一些很好的例子。
_.merge (Lodash only)
The second object will overwrite or add to the base object. undefined
values are not copied.
第二个对象将覆盖或添加到基本对象。未定义的值不会被复制。
var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
_.merge(obj, obj2);
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3"}
_.extend / _.assign
The second object will overwrite or add to the base object. undefined
will be copied.
第二个对象将覆盖或添加到基本对象。未定义将被复制。
var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
_.extend(obj, obj2);
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3", key4: undefined}
_.defaults
The second object contains defaults that will be added to base object if they don't exist. undefined
values will be copied if key already exists.
第二个对象包含将被添加到基对象的默认值,如果它们不存在的话。如果键已经存在,则将复制未定义的值。
var obj = {key3: "value3", key5: "value5"};
var obj2 = {key1: "value1", key2:"value2", key3: "valueDefault", key4: "valueDefault", key5: undefined};
_.defaults(obj, obj2);
console.log(obj);
// → {key3: "value3", key5: "value5", key1: "value1", key2: "value2", key4: "valueDefault"}
$.extend
In addition, it may be worthwhile mentioning jQuery.extend, it functions similar to _.merge and may be a better option if you already are using jQuery.
此外,值得一提的是jQuery。扩展,它的功能类似于_。合并,如果您已经在使用jQuery,这可能是一个更好的选择。
The second object will overwrite or add to the base object. undefined
values are not copied.
第二个对象将覆盖或添加到基本对象。未定义的值不会被复制。
var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
$.extend(obj, obj2);
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3"}
Object.assign()
It may be worth mentioning the ES6/ ES2015 Object.assign, it functions similar to _.merge and may be the best option if you already are using an ES6/ES2015 polyfill like Babel if you want to polyfill yourself.
值得一提的是ES6/ ES2015对象。赋值,它的函数类似于_。合并,如果你已经在使用ES6/ES2015的polyfill,比如Babel,如果你想自己进行polyfill的话,这可能是最好的选择。
The second object will overwrite or add to the base object. undefined
will be copied.
第二个对象将覆盖或添加到基本对象。未定义将被复制。
var obj = {key1: "value1", key2: "value2"};
var obj2 = {key2:"value4", key3: "value3", key4: undefined};
Object.assign(obj, obj2);
console.log(obj);
// → {key1: "value1", key2: "value4", key3: "value3", key4: undefined}
#3
69
Year 2017 answer: Object.assign()
Object.assign(dest, src1, src2, ...) merges objects.
对象。赋值(dest, src1, src2,…)合并对象。
It overwrites dest
with properties and values of (however many) source objects, then returns dest
.
它使用源对象(无论多少)的属性和值覆盖dest,然后返回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.assign()方法用于将所有可枚举的自身属性值从一个或多个源对象复制到目标对象。它将返回目标对象。
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()
.使用比Object.assign()更短的语法可以进行浅克隆(不包括原型)或对象合并。
Note that
Object.assign()
triggers setters whereas spread syntax doesn’t.注意Object.assign()触发器设置,而spread语法没有。
Live example
It works in current Chrome and current Firefox. They say it doesn’t work in current Edge.
它可以在当前的Chrome和Firefox中工作。他们说它在当前的边缘上不起作用。
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!
哎呀……我带走了。从未来走私信息是非法的。适时地掩盖!
#4
62
You could use either of these (provided key3 is the acutal key you want to use)
您可以使用其中任何一个(假设key3是您想要使用的acutal键)
arr[ 'key3' ] = value3;
or
或
arr.key3 = value3;
If key3 is a variable, then you should do:
如果key3是一个变量,那么您应该:
var key3 = 'a_key';
var value3 = 3;
arr[ key3 ] = value3;
After this, requesting arr.a_key
would return the value of value3
, a literal 3
.
在这之后,请求加勒比海盗。a_key将返回value3的值,一个文本3。
#5
26
arr.key3 = value3;
because your arr is not really an array... It's a prototype object. The real array would be:
因为arr不是一个数组…这是一个原型对象。真正的数组是:
var arr = [{key1: value1}, {key2: value2}];
but it's still not right. It should actually be:
但这还是不对的。它实际上应该:
var arr = [{key: key1, value: value1}, {key: key2, value: value2}];
#6
22
var employees = [];
employees.push({id:100,name:'Yashwant',age:30});
employees.push({id:200,name:'Mahesh',age:35});
#7
8
I know there is already an accepted answer for this but I thought I'd document my idea somewhere. Please [people] feel free to poke holes in this idea, as I'm not sure if it is the best solution... but I just put this together a few minutes ago:
我知道这个问题已经有了一个公认的答案,但我想我应该把我的想法记录下来。请[人们]随意在这个想法上戳洞,因为我不确定这是否是最好的解决办法……但我只是在几分钟前把这些放在一起:
Object.prototype.push = function( key, value ){
this[ key ] = value;
return this;
}
You would utilize it in this way:
你可以这样利用它:
var obj = {key1: value1, key2: value2};
obj.push( "key3", "value3" );
Since, the prototype function is returning this
you can continue to chain .push
's to the end of your obj
variable: obj.push(...).push(...).push(...);
由于原型函数正在返回这个,所以您可以继续链式。push's到obj变量的末尾:object .push(…).push(…).push(…).push(…).push(…);
Another feature is that you can pass an array or another object as the value in the push function arguments. See my fiddle for a working example: http://jsfiddle.net/7tEme/
另一个特性是,您可以将数组或其他对象作为push函数参数中的值传递。请参阅我的小提琴的工作示例:http://jsfiddle.net/7tEme/。
#8
8
You can create a class with the answer of @Ionuț G. Stan
您可以创建一个类与@Ionuțg·斯坦的答案
function obj(){
obj=new Object();
this.add=function(key,value){
obj[""+key+""]=value;
}
this.obj=obj
}
Creating a new object with the last class:
使用最后一个类创建一个新对象:
my_obj=new obj();
my_obj.add('key1', 'value1');
my_obj.add('key2', 'value2');
my_obj.add('key3','value3');
Printing the object
打印对象
console.log(my_obj.obj) // Return {key1: "value1", key2: "value2", key3: "value3"}
Printing a Key
打印一个关键
console.log(my_obj.obj["key3"]) //Return value3
I'm newbie in javascript, comments are welcome. Works for me.
我是javascript新手,欢迎评论。为我工作。
#9
6
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;
#10
6
Two most used ways already mentioned in most answers
在大多数答案中已经提到了两种最常用的方法
obj.key3 = "value3";
obj["key3"] = "value3";
One more way to define a property is using Object.defineProperty()
定义属性的另一种方法是使用Object.defineProperty()
Object.defineProperty(obj, 'key3', {
value: "value3", // undefined by default
enumerable: true, // false by default
configurable: true, // false by default
writable: true // false by default
});
This method is useful when you want to have more control while defining property. Property defined can be set as enumerable, configurable and writable by user.
当您想在定义属性时拥有更多的控件时,此方法是有用的。定义的属性可以设置为可枚举、可配置和用户可写。
#11
5
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:
Firebug的对象:
console.log(Comicbook);
returns:
返回:
[Object { name="Spiderman", value="11"}, Object { name="Marsipulami", value="18"}, Object { name="Garfield", value="2"}]
[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
在Comicbook对象中添加Object {name="Peanuts", value="12"}。
#12
5
Either obj['key3'] = value3
or obj.key3 = value3
will add the new pair to the obj
.
obj['key3'] = value3或obj。key3 = value3将向obj添加新对。
However, I know jQuery was not mentioned, but if you're using it, you can add the object through $.extend(obj,{key3: 'value3'})
. E.g.:
但是,我知道jQuery没有被提及,但是如果您使用它,您可以通过$添加对象。扩展(obj,{ key3:‘value3 })。例如:
var obj = {key1: 'value1', key2: 'value2'};
$('#ini').append(JSON.stringify(obj));
$.extend(obj,{key3: 'value3'});
$('#ext').append(JSON.stringify(obj));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="ini">Initial: </p>
<p id="ext">Extended: </p>
jQuery.extend(target[,object1][,objectN]) merges the contents of two or more objects together into the first object.
扩展(target[,object1][,objectN])将两个或多个对象的内容合并到第一个对象中。
And it also allows recursive adds/modifications with $.extend(true,object1,object2);
:
它还允许使用$.extend进行递归添加/修改(true,object1,object2);
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};
$("#ini").append(JSON.stringify(object1));
$.extend( true, object1, object2 );
$("#ext").append(JSON.stringify(object1));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="ini">Initial: </p>
<p id="ext">Extended: </p>
#13
4
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'
.
只有当key3的值为“key3”时,才会出现使用key3对对象进行键控的答案。
#14
4
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.
根据ECMA-262中定义的属性访问器(http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf, P67),有两种方法可以将属性添加到现有对象中。所有这两种方式,Javascript引擎都会对它们进行相同的处理。
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.
这样,您可以在方括号符号中使用表达式(包括IdentifierName)。
#15
3
A short and elegant way in next Javascript specification (candidate stage 3) is:
下一个Javascript规范(候选阶段3)中一个简短而优雅的方法是:
obj = { ... obj, ... { key3 : value3 } }
obj = {…obj,……{key3: value3}
A deeper discussion can be found in Object spread vs Object.assign and on Dr. Axel Rauschmayers site.
对对象展开与对象展开有更深层次的探讨。分配并在Axel Rauschmayers博士的网站上。
It works already in node.js since release 8.6.0.
它已经在node中工作了。自发布8.6.0 js。
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.
Vivaldi, Chrome, Opera和Firefox的最新版本也知道这个功能,但是Mirosoft直到今天才知道,无论是在ie还是Edge中。
#16
3
var arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];
var injectObj = {isActive:true, timestamp:new Date()};
// function to inject key values in all object of json array
function injectKeyValueInArray (array, keyValues){
return new Promise((resolve, reject) => {
if (!array.length)
return resolve(array);
array.forEach((object) => {
for (let key in keyValues) {
object[key] = keyValues[key]
}
});
resolve(array);
})
};
//call function to inject json key value in all array object
injectKeyValueInArray(arrOfObj,injectObj).then((newArrOfObj)=>{
console.log(newArrOfObj);
});
Output like this:-
输出:-
[ { name: 'eve',
isActive: true,
timestamp: 2017-12-16T16:03:53.083Z },
{ name: 'john',
isActive: true,
timestamp: 2017-12-16T16:03:53.083Z },
{ name: 'jane',
isActive: true,
timestamp: 2017-12-16T16:03:53.083Z } ]
#17
2
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);
}
#18
0
In order to prepend a key-value pair to an object so the for in works with that element first do this:
为了将键-值对前置到一个对象,for In与该元素一起工作,首先要做的是:
var nwrow = {'newkey': 'value' };
for(var column in row){
nwrow[column] = row[column];
}
row = nwrow;
#19
0
Best way to achieve same is stated below:
达到这一目标的最佳方法如下:
function getKey(key) {
return `${key}`;
}
var obj = {key1: "value1", key2: "value2", [getKey('key3')]: "value3"};
//console.log(obj);
#20
0
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.
因为这是过去的问题,而不是现在的问题。还有一个解决方案:将键和值传递给函数,就会得到一个map对象。
var map = {};
function addValueToMap(key, value) {
map[key] = map[key] || [];
map[key].push(value);
}
#21
-16
arr.push({key3: value3});