问题描述
我有两个数组: newParamArr [i]
和 paramVal [i]
。
newParamArr [i]
数组中的示例值:
[名称,年龄 ,电子邮件]
paramVal [i]
数组中的示例值:
[Jon,15,jon @ gmail.com]
Example values in the paramVal[i]
array:["Jon", "15", "[email protected]"]
I需要创建一个JavaScript对象,将数组中的所有项放在同一个对象中。例如
I need to create a JavaScript object that places all of the items in the array in the same object. For example
{newParamArr [0]:paramVal [0],newParamArr [1]:paramVal [1],...}
两个数组的长度始终相同,但数组的长度可以增加或减少。如... ...
The lengths of the two arrays are always the same, but the length of arrays can increase or decrease. As in...
newParamArr.length === paramVal.length
将始终返回true。
newParamArr.length === paramVal.length
will always returns true.
以下帖子均无法回答我的问题:
None of the below posts could help to answer my question:
推荐答案
你的意思是这个吗?
var keys = ['foo', 'bar', 'baz'];
var values = [11, 22, 33]
var result = {};
keys.forEach((key, i) => result[key] = values[i]);
console.log(result);
或者,您可以使用 Object.assign
result = Object.assign(...keys.map((k, i) => ({[k]: values[i]})))
或对象扩展语法(ES2018) :
or object spread syntax (ES2018):
result = keys.reduce((o, k, i) => ({...o, [k]: values[i]}), {})
如果您使用的是lodash,那么完全针对此类事情。
In case you're using lodash, there's _.zipObject exactly for this type of thing.
这篇关于从两个数组创建JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!