-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.ts
38 lines (37 loc) · 1.05 KB
/
Solution.ts
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
function jsonToMatrix(arr: any[]): (string | number | boolean | null)[] {
const dfs = (key: string, obj: any) => {
if (
typeof obj === 'number' ||
typeof obj === 'string' ||
typeof obj === 'boolean' ||
obj === null
) {
return { [key]: obj };
}
const res: any[] = [];
for (const [k, v] of Object.entries(obj)) {
const newKey = key ? `${key}.${k}` : `${k}`;
res.push(dfs(newKey, v));
}
return res.flat();
};
const kv = arr.map(obj => dfs('', obj));
const keys = [
...new Set(
kv
.flat()
.map(obj => Object.keys(obj))
.flat(),
),
].sort();
const ans: any[] = [keys];
for (const row of kv) {
const newRow: any[] = [];
for (const key of keys) {
const v = row.find(r => r.hasOwnProperty(key))?.[key];
newRow.push(v === undefined ? '' : v);
}
ans.push(newRow);
}
return ans;
}