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

Simply adding properties:

And we want to add prop2 : 2 to this object, these are the most convenient options:

  1. Dot operator: object.prop2 = 2;
  2. square brackets: object['prop2'] = 2;

So which one do we use then?

The dot operator is more clean syntax and should be used as a default (imo). However, the dot operator is not capable of adding dynamic keys to an object, which can be very useful in some cases. Here is an example:

const obj = {
  prop1: 1
}

const key = Math.random() > 0.5 ? 'key1' : 'key2';

obj[key] = 'this value has a dynamic key';

console.log(obj);

Merging objects:

When we want to merge the properties of 2 objects these are the most convenient options:

  1. Object.assign(), takes a target object as an argument, and one or more source objects and will merge them together. For example:

const object1 = {
  a: 1,
  b: 2,
};

const object2 = Object.assign({
  c: 3,
  d: 4
}, object1);

console.log(object2);

  1. Object spread operator ...

const obj = {
  prop1: 1,
  prop2: 2
}

const newObj = {
  ...obj,
  prop3: 3,
  prop4: 4
}

console.log(newObj);

Which one do we use?

  • The spread syntax is less verbose and has should be used as a default imo. Don't forgot to transpile this syntax to syntax which is supported by all browsers because it is relatively new.
  • Object.assign() is more dynamic because we have access to all objects which are passed in as arguments and can manipulate them before they get assigned to the new Object.
查看更多
刘海飞了
3楼-- · 2018-12-31 02:37

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:

console.log(Comicbook);

returns:

[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

查看更多
几人难应
4楼-- · 2018-12-31 02:39

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" 
//            }   
//       }
查看更多
像晚风撩人
5楼-- · 2018-12-31 02:42

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);
 }
查看更多
余欢
6楼-- · 2018-12-31 02:44

You could use either of these (provided key3 is the acutal key you want to use)

arr[ 'key3' ] = value3;

or

arr.key3 = value3;

If key3 is a variable, then you should do:

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.

查看更多
荒废的爱情
7楼-- · 2018-12-31 02:44

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

查看更多
登录 后发表回答