merge two arrays (keys and values) into an object

2019-01-25 17:10发布

问题:

This question already has an answer here:

  • Merge keys array and values array into an object in Javascript 8 answers

Is there a common Javascript/Coffeescript-specific idiom I can use to accomplish this? Mainly out of curiosity.

I have two arrays, one consisting of the desired keys and the other one consisting of the desired values, and I want to merge this in to an object.

keys = ['one', 'two', 'three']
values = ['a', 'b', 'c']

回答1:

var r = {},
    i,
    keys = ['one', 'two', 'three'],
    values = ['a', 'b', 'c'];

for (i = 0; i < keys.length; i++) {
    r[keys[i]] = values[i];
}


回答2:

keys = ['one', 'two', 'three']
values = ['a', 'b', 'c']

d = {}

for i, index in keys
    d[i] = values[index]

Explanation: In coffeescript you can iterate an array and get each item and its position on the array, or index. So you can then use this index to assign keys and values to a new object.



回答3:

As long as the two arrays are the same length, you can do this:

var hash = {};
var keys = ['one', 'two', 'three']
var values = ['a', 'b', 'c']

for (var i = 0; i < keys.length; i++)
    hash[keys[i]] = values[i];

console.log(hash['one'])
console.log(hash.two);