Last active
January 9, 2024 13:23
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); |
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
you could just do:
Object.fromEntries(keys.map((e, i) => [e, values[i]]));