如何将数组元素作为键分散到对象中,并为它们定义一些值?

发布于 2025-01-21 00:01:13 字数 228 浏览 1 评论 0 原文

假设我有一个数组:

const arr = ['a',  'b, 'c'];

我想创建一个像这样的对象:

{ 'a': true, 'b': true, 'c': true}

我该怎么做?

const obj = {...arr: true} 

没用

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夏日浅笑〃 2025-01-28 00:01:14

使用

const arr = ['a', 'b', 'c'];

const res = arr.reduce((acc, key) => ({ ...acc, [key]: true }), {});

console.log(res);

Using Array#reduce:

const arr = ['a', 'b', 'c'];

const res = arr.reduce((acc, key) => ({ ...acc, [key]: true }), {});

console.log(res);

森林迷了鹿 2025-01-28 00:01:14

是的,这不是一个有效的任务。想到的第一种方法 - 如果您想要那些酷的ES6单线 - 是:

const obj = Object.fromEntries(arr.map((el) => [el, true]));

Yeah, that's not a valid assignment. The first way that comes to mind - if you want one of those cool ES6 one-liners - would be:

const obj = Object.fromEntries(arr.map((el) => [el, true]));
梦情居士 2025-01-28 00:01:14

使用 object.assign 并传播数组(带有映射)。

const arr = ['a', 'b', 'c'];

const res = Object.assign({}, ...arr.map(key => ({[key]: true})));

console.log(res);

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);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文