Arash Howaida
Arash Howaida

Reputation: 2617

Construct Object From Two Arrays

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.

Upvotes: 2

Views: 125

Answers (4)

th3n3wguy
th3n3wguy

Reputation: 3737

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), {});

Upvotes: 1

Ele
Ele

Reputation: 33726

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

Upvotes: 2

Geoff Harper
Geoff Harper

Reputation: 122

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

Upvotes: 1

Mamun
Mamun

Reputation: 68933

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

Upvotes: 1

Related Questions