'How to create a Javascript object from an array of known keys, but with the values initialized to null?

I have a JS object from which I will extract an array of keys (using Object.keys()) and then I want to use those same keys to create a different object, but this time with its values initialized to null.

In Python, I would do something like:

list_of_keys = ["key_1", "key_2"]

# The * unpacks the list, could be thought as a JS spread operator
new_dict = dict.fromkeys(*list_of_keys)

And I would retrieve a new dictionary with all its values initialized to None as a default.

I don't seem to find a similar property or method in Javascript, however.

EDIT: If using ESLint, @CerebralFart answer (the for... of...) might trigger a complaint from the linter. It can be addressed here.



Solution 1:[1]

You can use reduce method to do it:

const object = { key_1: 'value_1', key_2: 'value_2', key_3: 'value_3' };

const new_object = Object.keys(object).reduce((accumulator, currentValue)=> {
  accumulator[currentValue] = null;
  return accumulator;
}, {});

console.log(new_object)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NeNaD