javascript 将两个数组(键和值)合并为一个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6921962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
merge two arrays (keys and values) into an object
提问by Jorge Israel Pe?a
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']
回答by bjornd
var r = {},
i,
keys = ['one', 'two', 'three'],
values = ['a', 'b', 'c'];
for (i = 0; i < keys.length; i++) {
r[keys[i]] = values[i];
}
回答by Luis Gonzalez
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中,您可以迭代一个数组并获取每个项目及其在数组或索引上的位置。因此,您可以使用此索引将键和值分配给新对象。
回答by Chris
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);