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

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.

.push() is for Arrays, not for objects.

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.

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

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.

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楼-- · 2018-12-31 02:32

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);
查看更多
情到深处是孤独
4楼-- · 2018-12-31 02:33

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;
查看更多
深知你不懂我心
5楼-- · 2018-12-31 02:34
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 } ]
查看更多
大哥的爱人
6楼-- · 2018-12-31 02:36

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:

The Array literal notation:

var arr = [];

The Array constructor notation:

var arr = new Array();
查看更多
泪湿衣
7楼-- · 2018-12-31 02:36

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.

查看更多
登录 后发表回答