Languages
[Edit]
EN

JavaScript - add key / value pair to object

3 points
Created by:
Aisha
418

In this article, we would like to show you how to add key / value pair to an object in JavaScript.

There are two ways to do that:

  1. Using dot notation,
  2. Using square bracket notation

1. Using dot notation

In the below example we create obj object with two key / value pairs.
We add key3 with 'value3' using dot notation, then we display whole obj object.

Runnable example:

// ONLINE-RUNNER:browser;

var obj = {
    key1: 'value1',
    key2: 'value2'
};

obj.key3 = 'value3';  // <-----  add a key / value pair using dot notation

console.log(JSON.stringify(obj, undefined, 4));

Output:

{
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}

2. Using square bracket notation

In the below example we create obj object with two key / value pairs.
We add key3 with 'value3' using square bracket notation, then we display whole obj object.

Note:
This approach is useful because you can replace 'key3' string with some variable which let us address key value dynamically using variable.

Runnable example:

// ONLINE-RUNNER:browser;

var obj = {
    key1: 'value1',
    key2: 'value2'
};

obj['key3'] = 'value3';  // <-----  add a key / value pair using square bracket notation

console.log(JSON.stringify(obj, undefined, 4));

Output:

{
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}

Alternative titles

  1. JavaScript - adding elements to object
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join