Skip to content

Instantly share code, notes, and snippets.

@ThomasG77
Last active Jan 18, 2022
Embed
What would you like to do?
Javascript equivalent to python dict(zip(['AB', 'CD', 'EF', 'GH'],[1, 2, 3, 4])) - 2 js arrays to one js object
var keys = ['AB', 'CD', 'EF', 'GH'];
var values = [1, 2, 3, 4];
// Equivalent to python dict(zip(['AB', 'CD', 'EF', 'GH'],[1, 2, 3, 4])) in javascript
function dictZip(key_array, val_array) {
if (key_array.length === val_array.length) {
return key_array.reduce((acc, curr, index) => {
acc[curr] = val_array[index];
return acc;
}, {});
} else {
console.error("Wrong length");
}
}
console.log(dictZip(keys, values));
@Emporea
Copy link

Emporea commented Jan 18, 2022

you could just do:

Object.fromEntries(keys.map((e, i) => [e, values[i]]));

@ThomasG77
Copy link
Author

ThomasG77 commented Jan 18, 2022

Completely right. Never changed the logic in the snippet since 2012 and then 2017 where no Object.fromEntries did not exist.
Method present only since "ES2019"
Thanks for the feedback

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment