8

I have a list of lists, each inner list has 2 items. I want to transform it into a dictionary.

const have = [['a', 1], ['b', 2]]
const want = {'a': 1, 'b': 2}

In python I would do

>>> dict([['a', 1], ['b', 2]])
{'a': 1, 'b': 2}

What is the easiest way (1-liner) to achieve this in JavaScript?

The easiest way I can think of is a 2-liner.

const have = [['a', 1], ['b', 2]]
const want = {}
have.forEach(([key, value]) => want[key] = value)
3
  • new Map([iterable]) is what you are looking for here. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Apr 1, 2019 at 23:03
  • Close enough, but I cannot JSON.stringify() that. Is there an easy way to turn it into a dict? Commented Apr 1, 2019 at 23:07
  • Thats fair, added an example using Array.prototype.reduce as well. That will work for you. Commented Apr 1, 2019 at 23:12

3 Answers 3

12

In the future it'll be:

 const want = Object.fromEntries(have);

It will hopefully be part of ES2019, and is already supported in some browsers. doc

Until the support gets better, your two-liner is the way to go.

Sign up to request clarification or add additional context in comments.

2 Comments

sadly there's no "official" polyfill on MDN
That is what I was looking for. I'd just make a polyfill using this API and wait for browser adoption. Thank you!
2

If you really must have this as a one-liner you could use reduce.

const have = [['a', 1], ['b', 2]];
const want = have.reduce((dict, [key, value]) => Object.assign(dict, {[key]: value}), {});

It's not very readable though and it creates a throwaway object for each element. I generally prefer readability over trying to get clever with one-liners.

1 Comment

or simply Object.assign(...have.map(([k,v]) => ({[k]: v}))), but this is horrible too.
1

Examples of using Map and Reduce.

I think because of you JSON.stringify() you will be wanting Reduce

// using Map
const have = [
  ['a', 1],
  ['b', 2]
];
let want = new Map(have);

console.log(want.get('a'));

// Using Reduce
want = have.reduce((a, v) => {
  a[v[0]] = v[1];
  return a;
}, {});

console.log(want);

console.log(JSON.stringify(want));

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.