How to add key-value pair in an object JavaScript?

One of the common tasks in JavaScript programming is adding key-value pairs to an object. Objects in JavaScript are collections of key-value pairs, so adding a new key-value pair is a simple task. Here’s how you can add a key-value pair in an object using JavaScript.

1. Using dot notation:

You can simply use the dot notation to add a new key-value pair to an object. Here’s an example:

“`
let myObject = {};
myObject.key = ‘value’;
“`

2. Using square brackets:

Another way to add a key-value pair to an object is by using square brackets. Here’s an example:

“`
let myObject = {};
myObject[‘key’] = ‘value’;
“`

3. Adding multiple key-value pairs:

You can also add multiple key-value pairs to an object using the same syntax. Here’s an example:

“`
let myObject = {};
myObject.key1 = ‘value1’;
myObject.key2 = ‘value2’;
“`

4. Adding nested key-value pairs:

If you want to add nested key-value pairs to an object, you can do so by creating objects inside objects. Here’s an example:

“`
let myObject = {};
myObject.key = {};
myObject.key.nestedKey = ‘nestedValue’;
“`

5. Overwriting existing key-value pair:

If you try to add a key that already exists in the object, it will simply overwrite the existing value. Here’s an example:

“`
let myObject = {key: ‘oldValue’};
myObject.key = ‘newValue’;
“`

6. Adding key with a variable name:

You can also use variables to dynamically add key-value pairs to an object. Here’s an example:

“`
let key = ‘dynamicKey’;
let myObject = {};
myObject[key] = ‘dynamicValue’;
“`

7. Adding key with a special character:

If you want to add a key with a special character, you can do so by using square brackets. Here’s an example:

“`
let myObject = {};
myObject[‘special-key’] = ‘specialValue’;
“`

8. Adding key with a number:

You can also add a key with a number as its name to an object. Here’s an example:

“`
let myObject = {};
myObject[1] = ‘numberValue’;
“`

9. Adding key with a function:

If you want to add a key with a function as its value, you can do so by defining a function and assigning it as a value. Here’s an example:

“`
let myObject = {};
myObject.key = function(){ console.log(‘Hello!’) };
“`

10. Adding key with an array:

You can also add a key with an array as its value to an object. Here’s an example:

“`
let myObject = {};
myObject.key = [‘value1’, ‘value2’];
“`

11. Adding key with an object:

If you want to add a key with an object as its value, you can do so by defining an object and assigning it as a value. Here’s an example:

“`
let myObject = {};
myObject.key = { nestedKey: ‘nestedValue’ };
“`

12. Adding key with undefined value:

If you want to add a key with an undefined value, you can do so simply by not assigning any value to the key. Here’s an example:

“`
let myObject = {};
myObject.key = undefined;
“`

Dive into the world of luxury with this video!


Your friends have asked us these questions - Check out the answers!

Leave a Comment