简体   繁体   中英

CoffeeScript - transform object into a matrix using comprehensions

I have an object of the form: {a: [1,2,3,4], b: [5,6,7,8]} and I want to transform it, using comprehensions, into an array of arrays of 3 items:

[
  ['a', 0, 1], ['a', 1, 2], ['a', 2, 3], ['a', 3, 4],
  ['b', 0, 5], ['b', 1, 6], ['b', 2, 7], ['b', 3, 8]
]

I tried this ( [x,y,v] for v, y in h for x, h of obj ) but it gives an array of two elements of 4 elements:

[ 
  [ [], [], [], [] ],
  [ [], [], [], [] ]
]

How can I skip the array of the second level?

It's easier to see when you split out the two comprehensions:

result = for x, h of obj
  for v, y in h 
    [x,y,v] 

Your result will be 2 levels deep, as each comprehension is returning an array.

First depth array will have one array for each element in your object.

Each of these arrays will contain the results for one key in your object


Best way around this is to push each of the 3 element arrays you want into a separate array.

result = []
for x, h of obj
  for v, y in h
    result.push [x,y,v]

Alternatively with the compact formatting:

result = []
result.push [x,y,v] for v, y in h for x, h of obj 

If you already have a utility library like lodash , you could use the flatten method. But this would involve another iteration over your arrays, so not practical if performance matters and you have very large datasets

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