将键数组和值数组合并到Javascript中的对象中

我有:

var keys = [ "height", "width" ]; var values = [ "12px", "24px" ]; 

我想把它转换成这个对象:

 { height: "12px", width: "24px" } 

在Python中,有简单的成语dict(zip(keys,values)) 。 有没有类似的jQuery或纯JavaScript,还是我必须做这个很长的路?

简单的JSfunction将是:

 function toObject(names, values) { var result = {}; for (var i = 0; i < names.length; i++) result[names[i]] = values[i]; return result; } 

当然,你也可以实际实现zip等function,因为JS支持更高阶的types,这使得这些function语言易于使用:D

使用lodash。

_.zipObject

 _.zipObject(['a', 'b'], [1, 2]); // ➜ { 'a': 1, 'b': 2 } 
 function combineObject( keys, values) { var obj = {}; if ( keys.length != values.length) return null; for (var index in keys) obj[keys[index]] = values[index]; return obj; }; var your_obj = combine( your_keys, your_values); 

您可以使用reduce()函数将键值对映射到对象。

 /** * Apply to an existing or new object, parallel arrays of key-value pairs. * * @param {string[]} keys - List of keys corresponding to their accociated values. * @param {object[]} vals - List of values corresponding to their accociated keys. * @param {object} [ref={}] - Optional reference to an existing object to apply to. * * @returns {object} - The modified or new object with the new key-value pairs applied. */ function toObject(keys, vals, ref) { return keys.length === vals.length ? keys.reduce(function(obj, key, index) { obj[key] = vals[index]; return obj; }, ref || {}) : null; } var keys = [ "height" , "width" ]; var values = [ "12px" , "24px" ]; document.body.innerHTML = '<pre>' + JSON.stringify(toObject(keys, values), null, 2) + '</pre>'; 

作为另一种解决scheme,我已经提到了:

  var result = {}; keys.forEach((key, idx) => result[key] = values[idx]); 

在jQuery-Utils项目中 , ArrayUtils模块实现了一个zip函数。

 //... zip: function(object, object2, iterator) { var output = []; var iterator = iterator || dummy; $.each(object, function(idx, i){ if (object2[idx]) { output.push([i, object2[idx]]); } }); return output; } //... 

奇怪而丑陋,但很小

这不是…传播一个,但只是踢。

 let arr1 = ['key1', 'key2', 'key3']; let arr2 = ['1', '2', '3']; let obj = (((o,a,b)=>(a.forEach((c,i)=>o[c]=b[i])||o)))({}, arr1, arr2); 

https://jsfiddle.net/x78gy4yu/

您可以使用Js ES 6新function轻松完成此操作:

 var keys = [ "height", "width" ]; var values = [ "12px", "24px" ]; var combineObject = { [keys.shift()] : values .shift(), [keys.shift()] : values .shift() }; console.log(combineObject); // { height: '12px', width: '24px' }