How can I add a key-value pair to an object in JavaScript?
Antek N
antek n profile pic

To add a key-value pair to an object in JavaScript, you can use either dot notation or bracket notation. Here's a step-by-step guide on how to achieve this: 1. Create an object:

1
2
3

   const obj = {};
   

Replace{} with the appropriate object variable or literal you want to add a key-value pair to. 2. Use dot notation: Dot notation allows you to add a key-value pair directly to an object by specifying the key as a property of the object and assigning it a value.

1
2
3

   obj.key = 'value';
   

Replace'key' with the desired key name, and'value' with the value you want to assign. In this example,obj.key = 'value' adds a new key-value pair to the objectobj. 3. Use bracket notation: Bracket notation provides an alternative way to add a key-value pair to an object. It allows you to use a variable or an expression as the key name enclosed in square brackets.

1
2
3
4
5

   const key = 'myKey';
   const value = 'myValue';
   obj[key] = value;
   

Replace'myKey' with the desired key name,'myValue' with the value you want to assign, andkey andvalue with the appropriate variables or expressions. In this example,obj[key] = value adds a new key-value pair to the objectobj using the values of thekey andvalue variables. 4. Add multiple key-value pairs at once: If you want to add multiple key-value pairs to an object, you can extend the object by assigning it an object literal with the desired properties and values.

1
2
3

   Object.assign(obj, { key1: 'value1', key2: 'value2' });
   

Replace'key1','value1','key2', and'value2' with the desired key-value pairs you want to add. In this example,Object.assign(obj, { key1: 'value1', key2: 'value2' }) adds the specified key-value pairs to the objectobj usingObject.assign(). Choose the method that best fits your requirements and the specific context in which you need to add a key-value pair to an object. Dot notation is recommended when the key name is a valid identifier, while bracket notation allows for more flexibility, especially when the key name is dynamic or requires special characters. TheObject.assign() method is useful when you want to add multiple key-value pairs at once.