Skip to content

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

javascriptadd keyvaluepair

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