I want to make a object with increasing number of keys ,for given number of items n e.g n=4 , so I want my object as obj {a1:" ",a2:" ",a3:" ",a4:" "} & my value should be "" empty string .
Asked
Active
Viewed 309 times
0
-
1Can you please share the code of what you've tried so far? – Traveling Tech Guy Mar 06 '19 at 18:01
-
Why not just use an array instead? Something like: `let a = ["a1", "a2", "a3", "a4"]` – Pedro Corso Mar 06 '19 at 18:07
2 Answers
2
You could create a little function that simply loops and sets keys
function createObj(n = 4, keyPrefeix = 'a') {
const obj = {};
for (let i = 1; i <= n; i++) {
obj[keyPrefeix + i] = '';
}
return obj;
}
console.log(createObj());
console.log(createObj(10, 'foo'));

baao
- 71,625
- 17
- 143
- 203