admin管理员组文章数量:1399474
Let say I have an array:
const arr = ['a', 'b, 'c'];
I want to create an object like this:
{ 'a': true, 'b': true, 'c': true}
How can I do this?
const obj = {...arr: true}
did not work
Let say I have an array:
const arr = ['a', 'b, 'c'];
I want to create an object like this:
{ 'a': true, 'b': true, 'c': true}
How can I do this?
const obj = {...arr: true}
did not work
Share Improve this question asked Apr 12, 2022 at 21:17 porFavorporFavor 4131 gold badge8 silver badges18 bronze badges 1- Please accept an answer as the solution to close the question – Majed Badawi Commented Apr 15, 2022 at 18:36
3 Answers
Reset to default 6Using Array#reduce
:
const arr = ['a', 'b', 'c'];
const res = arr.reduce((acc, key) => ({ ...acc, [key]: true }), {});
console.log(res);
Yeah, that's not a valid assignment. The first way that es to mind - if you want one of those cool ES6 one-liners - would be:
const obj = Object.fromEntries(arr.map((el) => [el, true]));
Using Object.assign
and spread the array (with map).
const arr = ['a', 'b', 'c'];
const res = Object.assign({}, ...arr.map(key => ({[key]: true})));
console.log(res);
本文标签:
版权声明:本文标题:javascript - How can I spread array elements into an object as the keys, and define some value for them? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744220737a2595851.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论