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

Laravel vs Node Js: Which One Is Good For What?

Introduction In the world of web development, selecting the correct framework is critical. Laravel and…

3 months ago

Docker Cheatsheet: Essential Commands and Explanations

Introduction By enabling containerization, Docker has transformed the way software is built, deployed, and managed.…

8 months ago

Difference between Memcached and REDIS – Secrets of Caching

Introduction Speed and efficiency are critical in the ever-changing world of web development. Effective caching…

8 months ago

How to Revert a Git Commit: A Simple Example

Introduction Git, a popular version control system in software development, enables developers to track changes,…

8 months ago

What is Git Stash and Why Do You Need It

Introduction Are you tired of grappling with tangled changes and unfinished work while using Git?…

8 months ago

Difference between git stash pop and git stash apply

Introduction Version control is essential in software development because it ensures that changes to a…

8 months ago