-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path2675-array-of-objects-to-matrix.ts
More file actions
53 lines (48 loc) · 1.51 KB
/
2675-array-of-objects-to-matrix.ts
File metadata and controls
53 lines (48 loc) · 1.51 KB
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
function jsonToMatrix(arr: any[]): (string | number | boolean | null)[][] {
const isObject = (x: any): x is object =>
x !== null && typeof x === "object";
const getKeys = (arg: any): string[] => {
if (!isObject(arg)) return [""];
return Object.keys(arg).reduce((acc: string[], curr: string) => {
return (
acc.push(
...getKeys(arg[curr]).map((x: string) =>
x ? `${curr}.${x}` : curr
)
),
acc
);
}, []);
};
const keys: string[] = [
...arr.reduce((acc: Set<string>, curr: any) => {
getKeys(curr).forEach((k: string) => acc.add(k));
return acc;
}, new Set<string>()),
].sort();
const getValue = (
obj: any,
path: string
): string | number | boolean | null => {
const paths: string[] = path.split(".");
let i = 0;
let value: any = obj;
while (i < paths.length) {
if (!isObject(value)) break;
value = value[paths[i++]];
}
if (i < paths.length || isObject(value) || value === undefined)
return "";
return value;
};
const matrix: (string | number | boolean | null)[][] = [keys];
arr.forEach((obj: any) => {
matrix.push(keys.map((key: string) => getValue(obj, key)));
});
return matrix;
}
const arr2 = [
{ b: 1, a: 2 },
{ b: 3, a: 4 },
];
console.log(jsonToMatrix(arr2));