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 In the world of web development, selecting the correct framework is critical. Laravel and…
Introduction By enabling containerization, Docker has transformed the way software is built, deployed, and managed.…
Introduction Speed and efficiency are critical in the ever-changing world of web development. Effective caching…
Introduction Git, a popular version control system in software development, enables developers to track changes,…
Introduction Are you tired of grappling with tangled changes and unfinished work while using Git?…
Introduction Version control is essential in software development because it ensures that changes to a…