Add key and value to javascript object

Add key and value to javascript object

Last updated: Dec 22, 2022
Reading time · 5 min

banner

# Table of Contents

# 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.

Copied!
const obj = name: 'Bobby'>; // ✅ using dot notation obj.age = 30; // ✅ using bracket notation obj['country'] = 'Chile'; // 👇️ console.log(obj); // 👇️ Chile console.log(obj['country']); // 👇️ Bobby console.log(obj['name']);

add key value pair to object

# 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.

Copied!
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

Copied!
const obj = name: 'Bobby'>; obj.age = 30; obj.name = 'Alice'; // 👇️ console.log(obj);

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

Copied!
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'; // 👇️ 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.

Copied!
const obj = >; const key = 'city'; obj[key] = 'Santiago'; // 👇️ console.log(obj);

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

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.

Copied!
const obj = >; obj[123] = 'hello'; console.log(obj); // 👉️ 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.

Copied!
const obj = country: 'Chile'>; Object.assign(obj, color: 'red', food: 'pizza'>); // 👇️️ console.log(obj);

add key value pair to object using object assign

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.

Copied!
const obj = country: 'Chile'>; Object.assign(obj, 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.
Copied!
let obj = name: 'Bobby'>; obj = . obj, 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.

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.

Copied!
let obj = name: 'Bobby'>; obj = . obj, 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.

Copied!
let obj = name: 'Bobby'>; const obj2 = id: 1>; obj = . obj2, . obj, 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.

Copied!
let obj = name: 'Bobby'>; obj = . obj, 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.

Copied!
const obj = name: 'Bobby'>; const newObj = . obj, name: 'Alice', country: 'Chile'>; // 👇️ console.log(newObj); // 👇️ 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.

Copied!
const obj = name: 'Bobby'>; Object.defineProperty(obj, 'age', value: 30, enumerable: true, configurable: true, writable: true, >); console.log(obj); // 👉️

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

# 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.

Источник

How to Add Key-Value Pairs to an Object

Working with objects is a common task in JavaScript. Objects are used to store data in the form of key-value pairs.

One of the most common tasks that developers often encounter is adding key-value pairs to an object.

There are multiple ways to add key-value pairs to an object in JavaScript. Let’s explore them one by one.

Object Introduction

Before we proceed, let’s have a quick overview of JavaScript objects. In JavaScript, objects are data structures that store key-value pairs. They are similar to real-life objects, where each property represents a characteristic or attribute of the object.

Objects are defined within curly braces <> and can hold various data types as values, including numbers, strings, arrays, and even other objects. Now, let’s explore different techniques to add key-value pairs to an object.

1. Using Dot Notation

One way to add a key-value pair to an object is by using the dot notation . This method is suitable when you know the key name in advance.

Here is an example of adding a key-value pair to an object using the dot notation.

const person = < name: "John", age: 30, >; person.city = "New York"; console.log(person);

In the above code snippet, we have an object called person with properties name and age . To add the city property, we can simply use dot notation ( person.city ) followed by the assignment operator ( = ) and the value we want to assign ( «New York» ). The resulting object will contain the added key-value pair.

2. Using Bracket Notation

Another way to add a key-value pair to an object is by using the bracket notation . This method is useful when the key name is stored in a variable or when it contains special characters.

Let’s see an example for this:

const car = < brand: "Toyota", >; const key = "color"; const value = "blue"; carAdd key and value to javascript object = value; console.log(car);

In the above example, we have an object called car with the property brand . To add a new key-value pair, we create variables key and value . Then, we use bracket notation ( carAdd key and value to javascript object ) to add the key-value pair dynamically.

Another example of using bracket notation to add a key-value pair to an object is when the key name contains special characters.

const person = < name: "John", age: 30, >; const key = "city name"; const value = "New York"; personAdd key and value to javascript object = value; console.log(person);

3. Using Object.assign()

Using the Object.assign() method you can add multiple key-value pairs to an object at once.

To add multiple key-value pairs to an object, you need to pass the object as the first argument and the key-value pairs as the second argument to the Object.assign() method.

const person = < name: "John" >; Object.assign(person, < age: 30, country: "USA", >); console.log(person);

In the above example, we have an object called person with properties name and age . To add multiple key-value pairs to the object, we use the Object.assign() method and pass the object as the first argument and the key-value pairs as the second argument.

4. Using Spread Operator

Using the spread operator ( . ) you can add multiple key-value pairs to an object at once.

To add multiple key-value pairs to an object, you need to pass the object as the first argument and the key-value pairs as the second argument to the spread operator.

const person = < name: "John" >; const newPerson = < . person, age: 30, country: "USA", >; console.log(newPerson);

In the above example, we have an object called person with properties name and age . To add multiple key-value pairs to the object, we use the spread operator ( . ) and pass the object as the first argument and the key-value pairs as the second argument.

5. Checking if a Key Already Exists

Before adding a key-value pair to an object, it’s important to check if the key already exists. If the key exists, you might want to update its value instead.

Here’s an example that demonstrates this concept:

const student = < name: "Emily", age: 21, >; if (student.hasOwnProperty("age")) < student.age = 22; >else < student.age = 21; >console.log(student);

In the above example, we have an object called student with properties name and age . Before adding a key-value pair to the object, we check if the key age already exists using the hasOwnProperty() method. If the key exists, we update its value. Otherwise, we add the key-value pair to the object.

6. Adding a Key-Value Pair to a Nested Object

Adding a key-value pair to a nested object is similar to adding a key-value pair to a normal object.

Here’s an example that demonstrates this concept:

const student = < name: "Emily", age: 21, address: < street: "123 Main St", city: "New York", >, >; student.address.country = "USA"; console.log(student);

In the above example, we have an object called student with properties name , age , and address . The address property is a nested object with properties street and city . To add a key-value pair to the nested object, we use the dot notation ( . ) and pass the key name and value.

7. Updating the Value of an Existing Key

Updating the value of an existing key is similar to adding a key-value pair to an object.

Here’s an example that demonstrates this concept:

const student = < name: "Emily", age: 21, >; student.age = 18; console.log(student);

In the above example, we have an object called student with properties name and age . To update the value of the age property, we use the dot notation ( . ) and pass the key name and value.

Conclusion

There are multiple ways to add a key-value pair to an object in JavaScript. You can use the dot notation ( . ), square bracket notation ( [] ), Object.assign() method, spread operator ( . ), etc.

It’s important to check if the key already exists before adding a key-value pair to an object. If the key exists, you might want to update its value instead.

That’s all for now. Happy Learning!

Источник

Читайте также:  Java combine two list
Оцените статью