Categories
JavaScript Answers

How to create JSON with JavaScript for loop?

Spread the love

Sometimes, we want to create JSON with JavaScript for loop.

In this article, we’ll look at how to create JSON with JavaScript for loop.

How to create JSON with JavaScript for loop?

To create JSON with JavaScript for loop, we can use a for-of loop.

For instance, we write

const sels = [
  //...
];
const json = {};

for (const sel of sels) {
  json[sel.id] = sel.value;
}

to loop through the object entries in the sels array with a for-of loop.

In it, we get the entry being looped through with sel.

We add the sel.id property into json and then assign sel.value to it.

sel.id returned string value would be the property name.

Conclusion

To create JSON with JavaScript for loop, we can use a for-of loop.

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 *