Reputation: 2698
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
Upvotes: 0
Views: 1168
Reputation: 370779
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.
Upvotes: 2