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
3 Answers
Reset to default 7You 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
版权声明:本文标题:javascript - Create object with list of keys - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741220664a2360908.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论