goodvibration
goodvibration

Reputation: 6206

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?

Upvotes: 0

Views: 63

Answers (4)

TopW3
TopW3

Reputation: 1527

Here is my solution.

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

Upvotes: 0

Elias Soares
Elias Soares

Reputation: 10254

You can use reduce:

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

Upvotes: 1

Addis
Addis

Reputation: 2530

You can use reduce, and empty object as the initial value for the accumulator and insert property-value pairs on it:

const keys = [1, 2, 3];

let result = keys.reduce((obj, key, idx) => { obj[key] = 'qwe'[idx]; return obj }, {});

console.log(result)

Upvotes: 0

goodvibration
goodvibration

Reputation: 6206

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...

Upvotes: 0

Related Questions