0

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?

4
  • [1, 2, 3].reduce((p, c, i) => (p[c] = "qwe"[i], p), {});, alternative: Object.fromEntries([1, 2, 3].map((e, i) => [e, "qwe"[i]])); Commented Nov 25, 2019 at 19:22
  • @ASDFGerte: Hmmm... that's even neater than the one I just found myself. Thanks!!! Commented Nov 25, 2019 at 19:25
  • @ASDFGerte: Was referring to your first (original) suggestion. Commented Nov 25, 2019 at 19:26
  • yeah, just writing some ways that come to mind. You already showed Object.assign, so i think we got all the common ways. Wonder if there are some unfeasible but fun ways. Commented Nov 25, 2019 at 19:29

4 Answers 4

1

You can use reduce:

keys.reduce((accumulator, value, index) => { accumulator[index] = "qwe".charAt(index); return accumulator; }, {})
Sign up to request clarification or add additional context in comments.

5 Comments

var a = (b) => b = 10 so a(5) returns 10
If someone notices you of your code not working, you could at least check by testing it, cause then you would see, that it actually doesnt. Instead of asking stuff that won't benefit anyone.
I really didn't tested, but your comment is not the reason of not work. I'm just explaining it to you. I'm writing from mobile, so can't test it
Assignments yield the right side value, which in your case is a character (string), and will mess up the next step of reduce completely. You need to return the actual object, as mentioned, as shown in my comment, and another answer.
0

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

Comments

0

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)

Comments

0

Here is my solution.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.