【发布时间】:2018-02-16 00:40:57
【问题描述】:
我有两个列表要组合为键值对:
keys = ['Jan 2016', 'Feb 2016', 'Mar 2016'];
values = ['janData', 'febData', 'marData'];
我想要的结果是:
dataMap = {
'Jan 2016': 'janData',
'Feb 2016': 'febData',
'Mar 2016': 'marData'
};
我查看了In Javascript a dictionary comprehension, or an Object `map`,发现在给定现有数组的情况下,可以使用.reduce() 或assign() 构建对象。但是,当我有 两个 数组时,我无法弄清楚如何调整这些方法。
问题:如何从两个现有数组构造我的dataMap 对象?
近年来,对象理解似乎得到了一些更新。 assign() 似乎很新,但也许它不是我任务的最佳工具。另外,我只使用原生 javascript。
【问题讨论】:
-
我想像这样使用 reduce:
var dataMap = keys.reduce((accumulator, currentValue, currentIndex) => { accumulator[currentValue] = values[currentIndex] }, {}) -
你真的应该尝试 lodash 来做这样的事情:
_.fromPairs(_.zip(keys, values))
标签: javascript