Hello Friends đź‘‹,

Welcome To Infinitbility! ❤️

JavaScript array of objects, everyone uses to pass and store multiple details in the array.

now, we are going to learn when we have already an array of objects and we want to add one more property in all array of objects or in a single object of the array then how to do.

let start today’s tutorial How to add key and value in an array of objects in javascript?

before jumping to how we can add key and value, let create an example array of objects which we can use in examples.

let arrOfObj = [
  { id: 1, name: 'infinit' },
  { id: 2, name: 'bility' },
  { id: 3, name: 'infinitbility' },
];

console.log("arrOfObj", arrOfObj);

First, let take an example of adding the is_active key with value in every array of objects.

const newArrOfObj = arrOfObj.map(
  (e) => ({ ...e, is_active: true })
);

console.log('newArrOfObj', newArrOfObj);

now, try to change any single object with an object index.

arrOfObj[2].age = "infinity";

console.log('arrOfObj', arrOfObj);

Here, our whole code practice with output.

let arrOfObj = [
  { id: 1, name: 'infinit' },
  { id: 2, name: 'bility' },
  { id: 3, name: 'infinitbility' },
];

console.log('arrOfObj', arrOfObj);

// change every objects of array
const newArrOfObj = arrOfObj.map(
  (e) => ({ ...e, is_active: true })
);

console.log('newArrOfObj', newArrOfObj);


// change single object of array
arrOfObj[2].age = "infinity";

console.log('arrOfObj', arrOfObj);

Output

Array of objects, Javascript, Example

Thanks for reading…