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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.