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.
How To Check Value Exists In An Array Using Javascript?
JavaScript Interview Questions And Answers
Node.Js Interview Questions And Answers
Introduction Git tags are an essential feature of version control systems, offering a simple way…
Introduction The methods that browsers employ to store data on a user's device are referred…
Introduction A well-known open-source VPN technology, OpenVPN provides strong protection for both people and businesses.…
Introduction Integrating Sentry into a Node.js, Express.js, and MongoDB backend project significantly enhances error tracking…
Introduction In the world of JavaScript development, efficiently managing asynchronous operations is essential. Asynchronous programming…
Introduction Let's Encrypt is a Certificate Authority (CA) that makes it simple to obtain and…