Categories
JavaScript Answers

How to add values to an array of objects dynamically in JavaScript?

Spread the love

To add values to an array of objects dynamically in JavaScript, we use the spread syntax.

For instance, we write

let data = [
  { label: "1", value: 12 },
  { label: "1", value: 12 },
  { label: "1", value: 12 },
];

data = [...data, { label: "2", value: 14 }];

to spread the entries in data with ... into a new array.

And then we add another object at the end of the new array.

We then assign the new array as the value of data.

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 *