Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to create JavaScript dictionary from Array of Arrays

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)
like image 326
Andrei Cioara Avatar asked Dec 17 '22 17:12

Andrei Cioara


1 Answers

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.

like image 120
Jonas Wilms Avatar answered Apr 08 '23 13:04

Jonas Wilms