将 2 个元素数组的 JavaScript 数组转换为对象键值对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26454655/
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
Convert JavaScript array of 2 element arrays into object key value pairs
提问by Fred Guest
What is the fastest algorithm for getting from something like this:
从这样的东西中获得最快的算法是什么:
var array = [ [1,'a'], [2,'b'], [3,'c'] ];
to something like this:
到这样的事情:
Object { 1: "a", 2: "b", 3: "c" }
so far this is what i've come up with:
到目前为止,这是我想出的:
function objectify(array) {
var object = {};
array.forEach(function(element) {
object[element[0]] = element[1];
});
return object;
}
which works fine, but it seems kind of clumsy. Is there a better way? Would something like reduce()work and would that be any faster?
这工作正常,但似乎有点笨拙。有没有更好的办法?像reduce()这样的东西会起作用吗,那会更快吗?
回答by Alnitak
You could indeed use Array.prototype.reduce
:
你确实可以使用Array.prototype.reduce
:
function objectify(array) {
return array.reduce(function(p, c) {
p[c[0]] = c[1];
return p;
}, {});
}
where p
is the result of the previous iteration, initially {}
, and c
is the current element of the array.
其中p
是前一次迭代的结果,最初{}
,并且c
是阵列的当前元素。
It's unlikely to be any faster than array.forEach
, but it is IMHO cleaner. I don't believe there's any simpler implementation than this.
它不太可能比 快array.forEach
,但恕我直言,它更干净。我认为没有比这更简单的实现了。
NB: a function to do exactly this already exists in the Underscorelibrary: _.object(array)
注意:Underscore库中已经存在执行此操作的函数:_.object(array)
回答by Phrogz
Terse version using modern syntax:
使用现代语法的简洁版本:
let objectify = a => a.reduce( (o,[k,v]) => (o[k]=v,o), {} );
I use this technique as part of a terse query string parser:
我将此技术用作简洁查询字符串解析器的一部分:
// Converts "?foo=bar&j=1&go" into { foo:'bar', j:'1', go:true }
function parseQueryString(qs) {
var q = decodeURIComponent;
return qs.replace(/^\?/,'').split('&').map(s => s.split('='))
.reduce((o,[k,v]) => (o[q(k)] = v?q(v):true, o), {});
}
回答by Penny Liu
With Object.fromEntries
, you can convert from Array
to Object
:
使用Object.fromEntries
,您可以从 转换Array
为Object
:
var array = [
[1, 'a'],
[2, 'b'],
[3, 'c']
];
var object = Object.fromEntries(array);
console.log(object);
回答by Uri Klar
Lodash has a _.fromPairs
method that does exactly that.
Lodash 有一个_.fromPairs
方法可以做到这一点。
From the documentation:_.fromPairs([['a', 1], ['b', 2]]);
// => { 'a': 1, 'b': 2 }
从文档:_.fromPairs([['a', 1], ['b', 2]]);
// => { 'a': 1, 'b': 2 }
回答by thefourtheye
You can wrap the entire thing within Array.prototype.reduce
, like this
你可以把整个东西都包裹在里面Array.prototype.reduce
,像这样
function objectify(array) {
return array.reduce(function(result, currentArray) {
result[currentArray[0]] = currentArray[1];
return result;
}, {});
}
console.log(objectify([ [1, 'a'], [2, 'b'], [3, 'c'] ]));
# { '1': 'a', '2': 'b', '3': 'c' }
We are just accumulating the key-value pairs in the result
object and finally the result of reduce
will be the result
object and we are returning it as the actual result.
我们只是在result
对象中累积键值对,最后将结果reduce
作为result
对象,我们将其作为实际结果返回。