-
Notifications
You must be signed in to change notification settings - Fork 0
/
array-of-objects-to-matrix.js
48 lines (40 loc) · 1.11 KB
/
array-of-objects-to-matrix.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
46
47
48
/**
* @param {Array} arr
* @return {Matrix}
*/
var jsonToMatrix = function(arr) {
const keyValuePairs = arr.map(v => getValue(v));
const keys = [...new Set(keyValuePairs.flat().map(obj => Object.keys(obj)[0]))].sort()
const res = [keys]
for (const row of keyValuePairs) {
res.push([])
for (const k of keys) {
const rowKeys = row.map(r => Object.keys(r)[0]);
const existKey = rowKeys.includes(k)
const n = res.length - 1
if (existKey) {
const v = row.find(r => Object.keys(r).includes(k));
res[n].push(v[k])
} else {
res[n].push('')
}
}
}
return res;
};
const getValue = (obj, key = '', res = []) => {
const isNumber = typeof obj === 'number'
const isString = typeof obj === 'string'
const isBoolean = typeof obj === 'boolean'
const isNull = obj === null
if (isNumber || isString || isBoolean || isNull) {
return {
[key]: obj
}
}
for (const [k, v] of Object.entries(obj)) {
const composeKey = key ? `${key}.${k}` : `${k}`;
res.push(getValue(v, composeKey))
}
return res.flat()
}