可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have:
var keys = [ "height", "width" ]; var values = [ "12px", "24px" ];
And I'd like to convert it into this object:
{ height: "12px", width: "24px" }
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?
回答1:
Simple JS function would be:
function toObject(names, values) { var result = {}; for (var i = 0; i
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
回答2:
use lodash.
_.zipObject
Example
回答3:
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);
回答4:
You could use a reduce()
function to map the key-value pairs to an object.
/** * 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 = '' + JSON.stringify(toObject(keys, values), null, 2) + '
';
回答5:
As an alternate solution, not already mentioned I think :
var result = {}; keys.forEach((key, idx) => result[key] = values[idx]);
回答6:
In the jQuery-Utils project, the ArrayUtils module has a zip function implemented.
//... 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; } //...
回答7:
weird and ugly but tiny
This isn't the ...spread one but just for kicks.
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/
回答8:
You can do this easily using Js ES 6 new feature :
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' }