将键数组和值数组合并到Javascript中的对象中 [英] Merge keys array and values array into an object in Javascript
本文介绍了将键数组和值数组合并到Javascript中的对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有:
var keys = [ "height", "width" ];
var values = [ "12px", "24px" ];
我想把它转换成这个对象:
And I'd like to convert it into this object:
{ height: "12px", width: "24px" }
在Python中,有简单的成语 dict(zip(keys,values))
。在jQuery或普通的Javascript中是否有类似的东西,或者我必须做很长的事情吗?
In Python, there's the simple idiom dict(zip(keys,values))
. Is there something similar in jQuery or plain Javascript, or do I have to do this the long way?
推荐答案
简单的JS函数会是:
function toObject(names, values) {
var result = {};
for (var i = 0; i < names.length; i++)
result[names[i]] = values[i];
return result;
}
当然你也可以实现zip等功能,因为JS支持更高使这些功能语言易于使用的订单类型:D
Of course you could also actually implement functions like zip, etc as JS supports higher order types which make these functional-language-isms easy :D
这篇关于将键数组和值数组合并到Javascript中的对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文