admin管理员组

文章数量:1287251

What is the concisest way to create an object from a list of keys, all set to the same value. For example,

const keys = [1, 2, 3, 4]
const value = 0

What is the tersest way to attain the object

{
  “1”: 0,
  “2”: 0,
  “3”: 0,
  “4”: 0
}

What is the concisest way to create an object from a list of keys, all set to the same value. For example,

const keys = [1, 2, 3, 4]
const value = 0

What is the tersest way to attain the object

{
  “1”: 0,
  “2”: 0,
  “3”: 0,
  “4”: 0
}
Share Improve this question asked Jun 16, 2020 at 11:00 12527481252748 15.4k34 gold badges116 silver badges241 bronze badges 1
  • Does this answer your question? Create object from array – Tschallacka Commented Jun 16, 2020 at 11:09
Add a ment  | 

3 Answers 3

Reset to default 7

You can use Object.fromEntries

const keys = [1, 2, 3, 4]
const value = 0

const result = Object.fromEntries(keys.map(k => [k, value]))

console.log(result)

Should probably be something among:

const keys = [1, 2, 3 ,4];
const value = 0;

console.log(
  keys.reduce((acc, key) => (acc[key] = value, acc), {})
);

The simplest way I can think of would be to use .reduce();

const keys = [1, 2, 3, 4]
const value = 0

const obj = keys.reduce((carry, item) => {
    carry[item] = value;
    return carry;
}, {});

console.log(obj);

本文标签: javascriptCreate object with list of keysStack Overflow