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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With