2

I have two lists that I want to combine as key value pairs:

keys = ['Jan 2016', 'Feb 2016', 'Mar 2016'];

values = ['janData', 'febData', 'marData'];

The desired outcome I want is:

dataMap = {
    'Jan 2016': 'janData',
    'Feb 2016': 'febData',
    'Mar 2016': 'marData'
};

I looked at In Javascript a dictionary comprehension, or an Object `map` and saw there are ways to build an object using .reduce() or assign() given an existing array. However I couldn't figure out how to adapt those methods when I have two arrays.

Question: How can I construct my dataMap object from two existing arrays?

It seems object comprehensions have gotten some updates in recent years. assign() seems to be pretty new, but maybe it's not the best tool for my task. Also, I'm using native javascript only.

Arash Howaida
  • 2,575
  • 2
  • 19
  • 50
  • I'd imagine using reduce something like this: ```var dataMap = keys.reduce((accumulator, currentValue, currentIndex) => { accumulator[currentValue] = values[currentIndex] }, {})``` – Varinder Feb 16 '18 at 00:45
  • You should really try lodash for stuff like this: `_.fromPairs(_.zip(keys, values))` – georg Feb 16 '18 at 01:32

4 Answers4

2

Use function forEach.

var keys = ['Jan 2016', 'Feb 2016', 'Mar 2016'];
var values = ['janData', 'febData', 'marData'];

let result = {};
keys.forEach((k, i) => result[k] = values[i]);

console.log(result);

You can initialize a Map object:

Map constructor

An Array or other iterable object whose elements are key-value pairs (arrays with two elements, e.g. [[ 1, 'one' ],[ 2, 'two' ]]). Each key-value pair is added to the new Map; null values are treated as undefined.

var keys = ['Jan 2016', 'Feb 2016', 'Mar 2016'];
var values = ['janData', 'febData', 'marData'];

let result = new Map(keys.map((k, i) => [[k], values[i]]));

for (let key of result.keys()) {
  console.log(`${key} = ${result.get(key)}`);
}

Resource

Ele
  • 33,468
  • 7
  • 37
  • 75
1

You can do the following with Array's forEach():

var keys = ['Jan 2016', 'Feb 2016', 'Mar 2016'];
var values = ['janData', 'febData', 'marData'];
var dataMap = {};
keys.forEach(function(k, i){
  dataMap[k] = values[i];
})

console.log(dataMap);
Mamun
  • 66,969
  • 9
  • 47
  • 59
1
let dataMap = {}

for (let month in keys) {
    const _key = keys[month]
    dataMap[_key] = values[month]
}

This answer depends on your arrays being in the "same" order

1

I know there are already a lot of really good answers on here, but here is another approach that you could take if you want a more "functional programming" approach:

const keys = ['Jan 2016', 'Feb 2016', 'Mar 2016'];
const values = ['janData', 'febData', 'marData'];
const dataMap = keys.map((key, i) => ({
    [key]: values[i]
  }))
  .reduce((key, val) => Object.assign({}, key, val), {});
th3n3wguy
  • 3,649
  • 2
  • 23
  • 30