-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
45 lines (38 loc) · 944 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
'use strict'
/**
* Transpose an Array of Objects to an Object of Arrays and vice versa
* Example:
* ```js
* var data = [{year: 2012, turnover: 20}, {year: 2013, turnover: 18}]
* var dataT = transpose(data);
* console.log(dataT); //{year: [2012, 2013], turnover: [20, 18]}
* ```
* @param {Array|Object} data
* @return {Object|Array}
*/
module.exports = function transpose (data) {
if (Array.isArray(data)) return transposeArray(data)
else return transposeObject(data)
}
function transposeObject (data) {
var res = []
var key, i
for (key in data) {
for (i = 0; i < data[key].length; i++) {
res[i] = res[i] || {}
if (data[key][i] !== undefined) res[i][key] = data[key][i]
}
}
return res
}
function transposeArray (data) {
var res = {}
var i, key
for (i = 0; i < data.length; i++) {
for (key in data[i]) {
res[key] = res[key] || []
res[key][i] = data[i][key]
}
}
return res
}