简体   繁体   中英

javascript - javascript version of Python's one-line list comprehension code

I'm a Python programmer, and learning how to write clean codes in JavaScript. I want to replicate the following python code using Javascript code:

array = [...] # some array
foo = [ x.data for x in array ] 
>>> foo = [ obj_1, obj_2, obj_3 ... ]

someDict = {'key_1': [0,1], 'key_2': [3,4], 'key_3': [5,6]} 
bar = [{key: someDict[key][i] for key in someDict.keys()} for i in range(2)]
>>> bar = [{'key_1': 0, 'key_2': 3, 'key_3': 5}, 
                {'key_1': 1, 'key_2': 4, 'key_3': 6}]

Is there any 'clean' way translating the above python code into a javascript code? Hopefully in one-line, not using 3-4 lines of for-loop code

For the first one, the function you're looking for is .map :

 const arr = [ { data: 'foo' }, { data: 'bar' } ]; console.log( arr.map(({ data }) => data) ); 

For the second, there isn't really any way around it other than iterating over each entry in the object, and assigning each item in the object values's array to the appropriate place in the accumulator, if you use reduce . Remember to destructure the arguments for minimal syntax noise:

 const someDict = {'key_1': [0,1], 'key_2': [3,4], 'key_3': [5,6]}; const result = Object.entries(someDict).reduce( (a, [key, [v0, v1]]) => { a[0][key] = v0; a[1][key] = v1; return a; }, [{},{}] ); console.log(result); 

It may not look as clean as list comprehensions, but you'll have to do something like the above to achieve your desired result, assuming you're working with vanilla JS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM