Skip to main content
Back to problems
#2675
Hard JavaScript

Array of objects to matrix

68.6% acceptance
Mar 31, 2026
134
73
Write a function that converts an array of objects arr into a matrix m. arr is an array of objects or arrays. Each item in the array can be deeply nested with child arrays and child objects. It can also contain numbers, strings, booleans, and null values. The first row m should be the column names. If there is no nesting, the column names are the unique keys within the objects. If there is nesting, the column names are the respective paths in the object separated by ".". Each of the remaining rows corresponds to an object in arr. Each value in the matrix corresponds to a value in an object. If a given object doesn't contain a value for a given column, the cell should contain an empty string "". The columns in the matrix should be in lexographically ascending order.

Solution

TypeScript
Time O(n²)
Space O(1)
LeetCode
solution.ts
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };

function jsonToMatrix(arr: JSONValue[]): (null | boolean | number | string)[][] {
  const flattenObj = (obj: JSONValue, prefix: string): Record<string, JSONValue> => {
    const result: Record<string, JSONValue> = {};
    if (obj === null || typeof obj !== 'object') {
      result[prefix] = obj;
      return result;
    }
    for (const key of Object.keys(obj)) {
      const newKey = prefix ? prefix + '.' + key : key;
      const nested = flattenObj((obj as any)[key], newKey);
      Object.assign(result, nested);
    }
    return result;
  };
  const flattened = arr.map(item => flattenObj(item, ''));
  const colSet = new Set<string>();
  for (const obj of flattened) {
    for (const key of Object.keys(obj)) {
      colSet.add(key);
    }
  }
  const cols = [...colSet].sort();
  const matrix: (null | boolean | number | string)[][] = [cols];
  for (const obj of flattened) {
    const row = cols.map(col => col in obj ? obj[col] as (null | boolean | number | string) : '');
    matrix.push(row);
  }
  return matrix;
};