0

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 .

ArUn GuPta
  • 23
  • 8

2 Answers2

2
var obj = {}
for (var i=1; i<=4; i++) {
  obj['a' + i] = "" 
}
gilamran
  • 7,090
  • 4
  • 31
  • 50
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