Skip to content

Instantly share code, notes, and snippets.

@ThomasG77
Last active January 9, 2024 13:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasG77/2186830 to your computer and use it in GitHub Desktop.
Save ThomasG77/2186830 to your computer and use it in GitHub Desktop.
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

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