0

So let's say I have an array and an empty object

let array = ["a", "b", "c", "d", "e", "f"]
let obj = {}

I'm trying to loop through the array, and add each element of that array as a key to the object with a value of 0. How do I do that? I've tried:

  for (let i = 0; i < array.length; i++){
    for (let key in obj) {
      key = array[i]
      obj[key] = 0
    }
  }

The output I'd suppose I'd like to get is something like

console.log({obj})

{a: 0, b: 0, c: 0, d: 0, e: 0, f: 0}
Noah M
  • 33
  • 1
  • 4

2 Answers2

5

for (let key in obj) doesn't make any sense because the object is empty originally - that will never iterate at all. Use

  for (let i = 0; i < array.length; i++){
    obj[array[i]] = 0;
  }

Or, more functionally, create the object all at once by mapping the array into an array of entries:

const obj = Object.fromEntries(array.map(
  prop => [prop, 0]
));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

You can use Array.prototype.reduce() like so:

const array = ["a", "b", "c", "d", "e", "f"];

const obj = array.reduce((acc, curr) => {
  acc[curr] = 0;
  return acc;
}, {});

console.log(obj);

Array.prototype.reduce()

zb22
  • 3,126
  • 3
  • 19
  • 34