0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

one more question, how would you do [data[i].some_func() for i in range(3)]?
I prefer using Array.from when creating arrays from scratch - Array.from({ length: 3}, (_, i) => data[i].some_func());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.