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)
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)
Share
Improve this question
asked Apr 1, 2019 at 22:59
Andrei CioaraAndrei Cioara
3,6647 gold badges40 silver badges64 bronze badges
3
|
3 Answers
Reset to default 11In 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 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.
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));
new Map([iterable])
is what you are looking for here. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Bibberty Commented Apr 1, 2019 at 23:03JSON.stringify()
that. Is there an easy way to turn it into a dict? – Andrei Cioara Commented Apr 1, 2019 at 23:07Array.prototype.reduce
as well. That will work for you. – Bibberty Commented Apr 1, 2019 at 23:12