-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path019 — 2675. Array of Objects to Matrix.js
66 lines (55 loc) · 1.31 KB
/
019 — 2675. 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* @param {Array} arr
* @return {Matrix}
*/
var jsonToMatrix = function(arr) {
const isObject = elem => elem instanceof Object
const getSub = (obj) => {
const map = new Map()
const setMap = (elem, preKey) => {
if (!isObject(elem)) {
map.set(preKey, elem)
return
}
const subMap = getSub(elem)
for (const entry of subMap.entries()) {
const symbol = `${preKey}.${entry[0]}`
map.set(symbol, entry[1])
}
}
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; i++) {
setMap(obj[i], `${i}`)
}
} else {
for (const key of Object.keys(obj)) {
setMap(obj[key], key)
}
}
return map
}
const map = getSub(arr)
const set = new Set()
for (const key of map.keys()) {
const i = key.indexOf('.')
const symbol = key.slice(i + 1)
set.add(symbol)
}
const keys = [...set].sort((a, b) => a < b ? -1 : 1)
const len = arr.length
const matrix = [keys]
for (let i = 1; i <= len; i++) {
if (keys.length === 0) {
matrix[i] = []
continue
}
for (let j = 0; j < keys.length; j++) {
const key = `${i - 1}.${keys[j]}`
if (!matrix[i]) {
matrix[i] = []
}
matrix[i][j] = map.has(key) ? map.get(key) : ""
}
}
return matrix
};