简体   繁体   English

将键数组转换为键值对对象

[英]Convert an array of keys into an object of key-value pairs

I know how to convert this:我知道如何转换这个:

const keys = [1, 2, 3];

To this:对此:

[{key: 1, val: "q"}, {key: 2, val: "w"}, {key: 3, val: "e"}]

With a single mapping statement:使用单个映射语句:

keys.map((x, i) => ({key: x, val: "qwe".charAt(i)}));

But I would actually like to get this:但我实际上想得到这个:

{1: "q", 2: "w", 3: "e"}

Is there a neat way to do this in a single statement similar to the one above?是否有一种巧妙的方法可以在与上述类似的单个语句中执行此操作?

您可以使用减少

keys.reduce((accumulator, value, index) => { accumulator[index] = "qwe".charAt(index); return accumulator; }, {})

Ahhh, got it:啊,明白了:

const objects = Object.assign({}, ...keys.map((x, i) => ({[x]: "qwe".charAt(i)})));

Though I would be happy to hear other suggestions as well as any notes on this one...尽管我很乐意听到其他建议以及有关此建议的任何说明...

You can use reduce, and empty object as the initial value for the accumulator and insert property-value pairs on it:您可以使用 reduce 和空对象作为累加器的初始值并在其上插入属性值对:

 const keys = [1, 2, 3]; let result = keys.reduce((obj, key, idx) => { obj[key] = 'qwe'[idx]; return obj }, {}); console.log(result)

Here is my solution.这是我的解决方案。

 const keys = [1, 2, 3]; const vals = "qwe"; const result = keys.reduce((prev, cur, idx) => ({ ...prev, [cur]: vals[idx] }), {});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM