最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Simple way to create JavaScript dictionary from Array of Arrays - Stack Overflow

programmeradmin0浏览0评论

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
  • 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:03
  • Close enough, but I cannot JSON.stringify() that. Is there an easy way to turn it into a dict? – Andrei Cioara Commented Apr 1, 2019 at 23:07
  • Thats fair, added an example using Array.prototype.reduce as well. That will work for you. – Bibberty Commented Apr 1, 2019 at 23:12
Add a comment  | 

3 Answers 3

Reset to default 11

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 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));

发布评论

评论列表(0)

  1. 暂无评论