简体   繁体   中英

How can I add a key/value pair to a Javascript object when the value is empty?

I need to add a new key to my Javascript object, obj. Using the method below works fine as long as I have a value to go with the key.

The method below inserts the actual characters "" into the value position. I want to add the new item "key3", but I want it to now appear in obj as "key3":{} .

Here is my code:

  //1.adding key/value pair var obj ={ "key1":{}, "key2":{} }; obj["key3"] = "test"; //obj now looks like: obj ={ "key1":{}, "key2":{}, "key3": test }; //2.adding key/value pair with empty value var obj ={ "key1":{}, "key2":{} }; obj["key3"] = ""; //obj now looks like: obj ={ "key1":{}, "key2":{}, "key3": "" }; //but I want obj to look like: var obj ={ "key1":{}, "key2":{}, "key3":{} }; 

Assign an object instead of a string.

var obj ={
    "key1":{},
    "key2":{}
};



obj["key3"] = {};



//////////////////////////////////////////////////////////////
New Object:

var obj ={
    "key1":{},
    "key2":{},
    "key3":{}
};

A functional, non-mutative approach with ES6 could look something like this:

const initialObject = {
    key1:{},
    key2:{}
};

const keysToAdd = {
  key3: {}
};

const updatedObject = Object.assign({}, initialObject, keysToAdd);

console.log(updatedObject);

JS Bin Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM