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.