Categories: JavaScript

How can I add a key/value pair to an JavaScript object?

In this article, you will learn how can I add a key/value pair to an JavaScript object. To understand this you have the basic knowledge of JavaScript Object.

Example 1 : Adding a key/value pair to an object using bracket notation

// add a key/value pair to an object

const person = {
    name: 'Ikhlaque',
    age: 29,
    gender: 'Male'
}
// add a key/value pair
person['height'] = 5.9;

console.log(person);

Example 2: Using the forEach() method to iterate through the array.

const array = [{id: 3}, {id: 2}];

array.forEach(object => {
  object.color = 'red';
});

// 👇️ [{id: 3, color: 'red'}, {id: 2, color: 'red'}]
console.log(arr);

The function that we pass to the forEach method will be called with each element in the array. With each iteration, we add a key/value pair to the current object.

Example 3: Using map function we can achieve same result as above.

const array = [{id: 3}, {id: 2}];

const arrWithColor = array.map(object => {
  return {...object, color: 'red'};
});

// 👇️ [{id: 3, color: 'red'}, {id: 2, color: 'red'}]
console.log(arrWithColor);

// 👇️ [{id: 3}, {id: 2}]
console.log(array);

The function that we pass to the Array.map method will be called with each element (object) in the array. We use the spread operator (…) to unpack each object’s key/value pairs and add an additional key/value pair.

Related Articles

How To Check Value Exists In An Array Using Javascript?

JavaScript Interview Questions And Answers

Node.Js Interview Questions And Answers

Pan Card Validation Using Javascript

How To Select Active Menu Item Using Jquery

Developer Diary

Share
Published by
Developer Diary

Recent Posts

Git Tag Cheat Sheet

Introduction Git tags are an essential feature of version control systems, offering a simple way…

2 months ago

Understanding Web Storage: Cookies, Local Storage

Introduction The methods that browsers employ to store data on a user's device are referred…

3 months ago

Setting up OpenVPN Access Server in Amazon VPC – AWS

Introduction A well-known open-source VPN technology, OpenVPN provides strong protection for both people and businesses.…

3 months ago

Enhance Error Tracking & Monitoring: Integrate Sentry with Node.js & Express.js

Introduction Integrating Sentry into a Node.js, Express.js, and MongoDB backend project significantly enhances error tracking…

3 months ago

Comparing Callbacks, Promises, and Async/Await in JavaScript

Introduction In the world of JavaScript development, efficiently managing asynchronous operations is essential. Asynchronous programming…

5 months ago

How To Secure Nginx with Let’s Encrypt on Ubuntu EC2 Instance

Introduction Let's Encrypt is a Certificate Authority (CA) that makes it simple to obtain and…

7 months ago