将两个数组(键和值)合并到一个对象中[重复]

时间:2022-04-10 08:51:08

This question already has an answer here:

这个问题在这里已有答案:

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

是否有一个常见的Javascript / Coffeescript特定的习惯用法可以用来实现这个目的?主要是出于好奇。

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']

3 个解决方案

#1


12  

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

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

#2


6  

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.

说明:在coffeescript中,您可以迭代数组并获取每个项及其在数组或索引上的位置。因此,您可以使用此索引将键和值分配给新对象。

#3


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

#1


12  

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

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

#2


6  

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.

说明:在coffeescript中,您可以迭代数组并获取每个项及其在数组或索引上的位置。因此,您可以使用此索引将键和值分配给新对象。

#3


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