Reputation: 3664
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)
Upvotes: 7
Views: 12086
Reputation: 6063
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.
Upvotes: 2
Reputation: 4768
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));
Upvotes: 1
Reputation: 138267
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.
Upvotes: 11