Last updated: Mar 1, 2024
Reading timeยท7 min
There are multiple ways to add a key/value pair to an object:
[]
notation, e.g. obj['name'] = 'John'
..
notation, e.g. obj.name = 'John'
.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.
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']);
The first statement adds a key-value pair to the object using dot .
notation.
It is more concise and direct than using bracket []
notation.
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);
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.
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);
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.
const obj = {}; const key = 'city'; obj[key] = 'Santiago'; // ๐๏ธ {city: 'Santiago'} console.log(obj);
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.
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.
.
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.
The Object.assign()
method copies the key/value pairs of one or more objects
into a target object and returns the modified target object.
const obj = {country: 'Chile'}; Object.assign(obj, {color: 'red', food: 'pizza'}); // ๐๏ธ๏ธ {country: 'Chile', color: 'red', food: 'pizza'} console.log(obj);
The arguments we passed to the Object.assign()
method are:
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.
const obj = {country: 'Chile'}; Object.assign(obj, {first: 'Bobby', last: 'Hadz'}); // ๐๏ธ๏ธ { country: 'Chile', first: 'Bobby', last: 'Hadz' } console.log(obj);
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 (...)
.
This is a three-step process:
let
keyword.let obj = {name: 'Bobby'}; obj = {...obj, color: 'green'}; // ๐๏ธ {name: 'Bobby', color: 'green'} console.log(obj);
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.
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.
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.
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.
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.
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.
You can also use the Object.defineProperty() method to add a key-value pair to an object.
const obj = {name: 'Bobby'}; Object.defineProperty(obj, 'age', { value: 30, enumerable: true, configurable: true, writable: true, }); console.log(obj); // ๐๏ธ { name: 'Bobby', age: 30 }
The method defines a new property on an object or modifies an existing property.
The arguments we passed to the method are:
Here are the properties the descriptor
object takes:
true
, the property is iterated over in loops. Defaults to
false
.false
, the property cannot be deleted or changed. Defaults
to false
.false
, the value of the property cannot be changedI've also written an article on how to add a key-value pair to all objects in an array.
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.
let obj = {two: 2, three: 3}; obj = {one: 1, ...obj}; console.log(obj); // ๐๏ธ {one: 1, two: 2, three: 3}
We used the spread syntax (...) to unpack the key-value pairs of an object into a new object.
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.
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.
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.
Object.assign()
The Object.assign()
method copies the properties from one or more objects to a
target object and returns the result.
let obj = {two: 2, three: 3}; obj = Object.assign({one: 1}, obj); console.log(obj); // ๐๏ธ {one: 1, two: 2, three: 3}
The Object.assign()
method copies all of the properties from a source
object
to a target
object.
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:
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.
let obj = {two: 2, three: 3}; obj = Object.assign({one: 1}, obj); for (const key in obj) { console.log(key); // ๐๏ธ one, two, three }
Which approach you pick is a matter of personal preference. I'd use the spread syntax (...) as I find it more readable and intuitive.
You can learn more about the related topics by checking out the following tutorials: