Categories
JavaScript Answers

How to add key value pair to all objects in array with JavaScript?

Spread the love

To add key value pair to all objects in array with JavaScript, we use the spread operator.

For instance, we write

const arr = [{ name: "eve" }, { name: "john" }, { name: "jane" }];
const newArr = arr.map((v) => ({ ...v, isActive: true }));

to call arr.map with a callback that returns an object with the properties in v spread into a new object.

And then we add the isActive property to the object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *