Skip to content

Instantly share code, notes, and snippets.

@vncsna
Forked from dschep/py-comp-to-js.md
Created December 10, 2022 14:11
Show Gist options
  • Save vncsna/a2611f6bf92f9499c4e4fa3454a0aba9 to your computer and use it in GitHub Desktop.
Save vncsna/a2611f6bf92f9499c4e4fa3454a0aba9 to your computer and use it in GitHub Desktop.
Python Comprehensions to JS

Python list & dict comprehensions translated to JavasScript

Comprehensions are a really useful feature of Python that aren't available in JavaScript (or many languages). These concepts of course can be tranlsated into using map instead. But especially the dictionaries are a bit trickier.

Lists / Arrays

>>> foobar = range(5)
>>> [x + 1 for x in foobar]
[1, 2, 3, 4, 5]
# Intermediate translation
>>> map(lambda x: x + 1, foobar)
[1, 2, 3, 4, 5]

becomes:

> foobar = [0, 5, 3, 2]
[ 0, 5, 3, 2 ]
> foobar.map(x => x+1)
[ 1, 6, 4, 3 ]

Dictionaries / Objects

foobar = [{'key': 'fasdf', 'value': 'asfasdfaf'}, {'key': 'fassdfsddf', 'value': 'asdfaf'}]
>>> {x['key']: x['value'] for x in foobar}
{'fasdf': 'asfasdfaf', 'fassdfsddf': 'asdfaf'}
>>> # Intermediate translation to map
... dict(map(lambda x: (x['key'], x['value']), foobar))
{'fasdf': 'asfasdfaf', 'fassdfsddf': 'asdfaf'}

becomes:

> foobar = [{'key': 'fasdf', 'value': 'asfasdfaf'}, {'key': 'fassdfsddf', 'value': 'asdfaf'}]
[ { key: 'fasdf', value: 'asfasdfaf' },
  { key: 'fassdfsddf', value: 'asdfaf' } ]
> Object.fromEntries(foobar.map(x => [x.key, x.value]))
{ fasdf: 'asfasdfaf', fassdfsddf: 'asdfaf' }

dict->dict / obj->obj

>>> foobar = {'fasdf': 'asfasdfaf', 'fassdfsddf': 'asdfaf'}
>>> {key: val.upper() for key, val in foobar.items()}
{'fasdf': 'ASFASDFAF', 'fassdfsddf': 'ASDFAF'}

becomes:

foobar = {fasdf: 'asfasdfaf', fassdfsddf: 'asdfaf'}
Object.fromEntries(Object.entries(foobar).map(([key, value]) => [key, value.toUpperCase()]))
{ fasdf: 'ASFASDFAF', fassdfsddf: 'ASDFAF' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment