I have this Javascript code with a JSON variable that works well.
var valuesJSON = {
projects: {
0: {value: 0, price: 0},
1: {value: 0, price: 0},
2: {value: 0, price: 0},
3: {value: 0, price: 0},
4: {value: 0, price: 0},
5: {value: 0, price: 0},
6: {value: 0, price: 0},
7: {value: 0, price: 0},
}
}
I want to make it more scalable, so that it will read the number of entries from a constant. I tried the following but the for loop in the variable is not allowed. Any ideas?
const NUM_PROJECTS = 8
var valuesJSON = {
projects: {
for (var i=0; i < NUM_PROJECTS; i++) {
i: {value: 0, price: 0},
}
}
}
You need to add properties to projects using for loop. Bracket notation needs to used since variable is being used as key.
//Create object
var valuesJSON = {
projects : {}
}
//Iterate and add properties
for (var i = 0; i < NUM_PROJECTS; i++) {
valuesJSON.projects[i] = {
value: 0,
price: 0
}
}
You could iterate with NUM_PROJECTS and generate new properties with the wanted result.
const NUM_PROJECTS = 8
var valuesJSON = { projects: {}};
for (var i = 0; i < NUM_PROJECTS; i++) {
valuesJSON.projects[i] = { value: 0, price: 0 };
}
console.log(valuesJSON);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With