Array of Objects to Matrix
Hard
Solution
/* eslint-disable @typescript-eslint/no-explicit-any */
export function jsonToMatrix(arr: any[]): (string | number | boolean | null)[][] {
const isObject = (obj: any) => obj !== null && typeof obj === 'object';
const getKeys = (obj: any): string[] => {
if (!isObject(obj)) {
return [''];
}
const keys: string[] = [];
for (const [key, value] of Object.entries(obj)) {
for (const nestedKey of getKeys(value)) {
keys.push(nestedKey ? `${key}.${nestedKey}` : key);
}
}
return keys;
};
const getValue = (obj: any, path: string) => {
const paths = path.split('.');
let value = obj;
for (const p of paths) {
if (!isObject(value)) {
return '';
}
value = value[p];
}
if (isObject(value) || value === undefined) {
return '';
}
return value;
};
const keySet = new Set<string>();
arr.forEach((value) => {
getKeys(value).forEach((key) => keySet.add(key));
});
const keys = [...keySet].sort();
const matrix: (string | number | boolean | null)[][] = [keys];
arr.forEach((obj: any) => {
matrix.push(keys.map((key: string) => getValue(obj, key)));
});
return matrix;
}