How to Add a Key/Value pair to an Object in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 1, 2024
7 min

banner

# Table of Contents

  1. Add a Key/Value pair to an Object in JavaScript
  2. Add a Key/Value pair to an Object using Object.assign()
  3. Add a Property to the Beginning of an Object in JavaScript

# Add a Key/Value pair to an Object in JavaScript

There are multiple ways to add a key/value pair to an object:

  • Use bracket [] notation, e.g. obj['name'] = 'John'.
  • Use dot . notation, e.g. obj.name = 'John'.
  • Use the Object.assign() method, passing it a target and source objects as arguments.

Here is an example of adding key-value pairs to an object using dot . and bracket [] notation.

index.js
const obj = {name: 'Bobby'}; // โœ… using dot notation obj.age = 30; // โœ… using bracket notation obj['country'] = 'Chile'; // ๐Ÿ‘‡๏ธ {name: 'Bobby', age: 30, country: 'Chile'} console.log(obj); // ๐Ÿ‘‡๏ธ Chile console.log(obj['country']); // ๐Ÿ‘‡๏ธ Bobby console.log(obj['name']);

add key value pair to object

The code for this article is available on GitHub

# Using dot notation to add a key-value pair to an object

The first statement adds a key-value pair to the object using dot . notation. It is more concise and direct than using bracket [] notation.

index.js
const obj = {name: 'Bobby'}; obj.age = 30; obj.country = 'Chile'; obj.tasks = ['walk the dog', 'cook dinner']; // { // name: 'Bobby', // age: 30, // country: 'Chile', // tasks: [ 'walk the dog', 'cook dinner' ] // } console.log(obj);

using dot notation to add key value pair to object

If a key with the supplied name already exists in the object, its value gets updated.
index.js
const obj = {name: 'Bobby'}; obj.age = 30; obj.name = 'Alice'; // ๐Ÿ‘‡๏ธ { name: 'Alice', age: 30 } console.log(obj);

If the name of the key contains spaces or hyphens, you have to use square brackets.

index.js
const obj = {}; // โ›”๏ธ Cannot use dot notation if the key contains spaces or hyphens // obj.my-country = 30; // โ›”๏ธ SyntaxError // โœ… Can always use square brackets obj['my-country'] = 'Chile'; // ๐Ÿ‘ˆ๏ธ Works obj['full name'] = 'Bobby Hadz'; // ๐Ÿ‘‡๏ธ { 'my-country': 'Chile', 'full name': 'Bobby Hadz' } console.log(obj);

# Use bracket notation when the name of the key is in a variable

You must also use bracket notation [] when you don't know the name of the key in advance and you need to dynamically name the key.

index.js
const obj = {}; const key = 'city'; obj[key] = 'Santiago'; // ๐Ÿ‘‡๏ธ {city: 'Santiago'} console.log(obj);

use bracket notation when the name of the key is in variable

The code for this article is available on GitHub
We have the name of the key stored in a variable, so we can't use dot notation to add the key-value pair to the object.

We didn't wrap the value between the square brackets in quotes because it is a variable whose value we use for the name of the key.

You should also use bracket notation if your keys start with a number.

index.js
const obj = {}; obj[123] = 'hello'; console.log(obj); // ๐Ÿ‘‰๏ธ { '123': 'hello' } console.log(obj[123]); // ๐Ÿ‘‰๏ธ hello

The dot notation syntax cannot be used to add numeric keys to an object or keys that start with a number.

Most programmers use dot . notation to add key-value pairs to objects until they have to use square brackets [].

The next most common way to add a key-value pair to an object is to use the Object.assign() method.

# Add a Key/Value pair to an Object using Object.assign()

The Object.assign() method copies the key/value pairs of one or more objects into a target object and returns the modified target object.

index.js
const obj = {country: 'Chile'}; Object.assign(obj, {color: 'red', food: 'pizza'}); // ๐Ÿ‘‡๏ธ๏ธ {country: 'Chile', color: 'red', food: 'pizza'} console.log(obj);

add key value pair to object using object assign

The code for this article is available on GitHub

The arguments we passed to the Object.assign() method are:

  1. the target object - the object to which the provided properties will be applied.
  2. the source object(s) - one or more objects that contain the properties we want to apply to the target object.

You can imagine that the key-value pairs of the object we passed as the second argument to Object.assign(), get copied into the object we supplied for the first argument.

index.js
const obj = {country: 'Chile'}; Object.assign(obj, {first: 'Bobby', last: 'Hadz'}); // ๐Ÿ‘‡๏ธ๏ธ { country: 'Chile', first: 'Bobby', last: 'Hadz' } console.log(obj);
The Object.assign() method is very convenient when you have to add multiple key-value pairs to an object.

Another common approach used to add key-value pairs to an object is to use the spread syntax (...).

# Add a Key/Value pair to an Object using spread syntax (...)

This is a three-step process:

  1. Declare the object variable using the let keyword.
  2. Use the spread syntax (...) to unpack the object into a new object.
  3. Add a key-value pair to the new object.
index.js
let obj = {name: 'Bobby'}; obj = {...obj, color: 'green'}; // ๐Ÿ‘‡๏ธ {name: 'Bobby', color: 'green'} console.log(obj);
The code for this article is available on GitHub

An easy way to think about the spread syntax (...) is that we are unpacking the key/value pairs of the object into a new object.

We used the let keyword when declaring the obj variable because variables declared using const cannot be reassigned.

When using this approach, we create a new object by using the key-value pairs of an existing object and adding one or more key-value pairs.

You can use the same approach to add multiple key-value pairs to the object in the same statement.

index.js
let obj = {name: 'Bobby'}; obj = {...obj, color: 'green', country: 'Chile'}; // ๐Ÿ‘‡๏ธ { name: 'Bobby', color: 'green', country: 'Chile' } console.log(obj);

You can use the spread syntax (...) to unpack multiple objects before you add key-value pairs to the new object.

index.js
let obj = {name: 'Bobby'}; const obj2 = {id: 1}; obj = {...obj2, ...obj, age: 30, country: 'Chile'}; // ๐Ÿ‘‡๏ธ { id: 1, name: 'Bobby', age: 30, country: 'Chile' } console.log(obj);

You can override the value of some of the object's properties by specifying the key-value pairs after unpacking the object.

index.js
let obj = {name: 'Bobby'}; obj = {...obj, name: 'Alice', country: 'Chile'}; // ๐Ÿ‘‡๏ธ { name: 'Alice', country: 'Chile' } console.log(obj);

The existing object has a name key whose value we replaced by adding a name key with a different value after unpacking the object.

If you don't want to change the original object, declare a new variable.

index.js
const obj = {name: 'Bobby'}; const newObj = {...obj, name: 'Alice', country: 'Chile'}; // ๐Ÿ‘‡๏ธ { name: 'Alice', country: 'Chile' } console.log(newObj); // ๐Ÿ‘‡๏ธ { name: 'Bobby' } console.log(obj);

We declared a new variable that stores an object and added key-value pairs to the new variable.

The original object remains unchanged.

# Add a Key/Value pair to an Object using Object.defineProperty()

You can also use the Object.defineProperty() method to add a key-value pair to an object.

index.js
const obj = {name: 'Bobby'}; Object.defineProperty(obj, 'age', { value: 30, enumerable: true, configurable: true, writable: true, }); console.log(obj); // ๐Ÿ‘‰๏ธ { name: 'Bobby', age: 30 }
The code for this article is available on GitHub

The method defines a new property on an object or modifies an existing property.

The arguments we passed to the method are:

  1. The object on which to define the property.
  2. The name of the property.
  3. The descriptor for the property that is being defined.

Here are the properties the descriptor object takes:

  • enumerable - if true, the property is iterated over in loops. Defaults to false.
  • configurable - if false, the property cannot be deleted or changed. Defaults to false.
  • writable - if false, the value of the property cannot be changed

I've also written an article on how to add a key-value pair to all objects in an array.

# Add a Property to the Beginning of an Object in Javascript

Use the spread syntax (...) to add a property to the beginning of an object, e.g. obj = {one: 1, ...obj};.

The spread syntax will unpack the key-value pairs of the object after the added property.

index.js
let obj = {two: 2, three: 3}; obj = {one: 1, ...obj}; console.log(obj); // ๐Ÿ‘‰๏ธ {one: 1, two: 2, three: 3}

add property to beginning of object

The code for this article is available on GitHub

We used the spread syntax (...) to unpack the key-value pairs of an object into a new object.

index.js
let obj = {two: 2, three: 3}; const newObj = {...obj}; console.log(newObj); // ๐Ÿ‘‰๏ธ {two: 2, three: 3}

The code sample uses the spread syntax (...) to create a shallow copy of an object.

We need to add a property to the beginning of the object, so we unpack the existing key-value pairs after the property.

index.js
let obj = {two: 2, three: 3}; obj = {one: 1, ...obj}; // ๐Ÿ‘‡๏ธ { one: 1, two: 2, three: 3 } console.log(obj);

We added the property at the beginning of the object, so if the property is set in the existing object, it would get overridden.

index.js
let obj = {one: 1000, two: 2, three: 3}; obj = {one: 1, ...obj}; // ๐Ÿ‘‡๏ธ { one: 1000, two: 2, three: 3 } console.log(obj);

The one property already exists on the object, so even though we added the property to the beginning of the object, the last value of the specified property wins.

An alternative approach is to use the Object.assign() method.

# Add a property to the beginning of an Object using Object.assign()

The Object.assign() method copies the properties from one or more objects to a target object and returns the result.

index.js
let obj = {two: 2, three: 3}; obj = Object.assign({one: 1}, obj); console.log(obj); // ๐Ÿ‘‰๏ธ {one: 1, two: 2, three: 3}

add property to beginning of object using object assign

The code for this article is available on GitHub

The Object.assign() method copies all of the properties from a source object to a target object.

index.js
const obj = Object.assign({a: 1}, {b: 2}, {c: 3}); console.log(obj); // ๐Ÿ‘‰๏ธ { a: 1, b: 2, c: 3 }

The Object.assign() method takes 2 parameters:

  1. the target object - the object to which the sources' properties are applied
  2. the sources - the source objects that contain the properties to be applied to the target object.

The method returns the target object with the provided properties applied.

The key-value pairs of the second and third objects got copied into the first object.

This enables you to add one or more properties to the beginning of the object.

The ordering would be respected when iterating over the object, just like with the spread syntax.

index.js
let obj = {two: 2, three: 3}; obj = Object.assign({one: 1}, obj); for (const key in obj) { console.log(key); // ๐Ÿ‘‰๏ธ one, two, three }

ordering when iterating object is preserved

Which approach you pick is a matter of personal preference. I'd use the spread syntax (...) as I find it more readable and intuitive.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev