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:46

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;
查看更多
只靠听说
3楼-- · 2018-12-31 02:47

You can create a class with the answer of @Ionuț G. Stan

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.

查看更多
若你有天会懂
4楼-- · 2018-12-31 02:51
arr.key3 = value3;

because your arr is not really an array... It's a prototype object. The real array would be:

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}];
查看更多
初与友歌
5楼-- · 2018-12-31 02:51

Either obj['key3'] = value3 or obj.key3 = value3 will add the new pair to the 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.:

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.

And it also allows recursive adds/modifications with $.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>

查看更多
零度萤火
6楼-- · 2018-12-31 02:51

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'.

查看更多
无色无味的生活
7楼-- · 2018-12-31 02:52

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

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/

查看更多
登录 后发表回答