Turn an array of nested objects into a table: dotted column paths, sorted headers and blanks for missing values

mediumAbout 25 minutesUpdated CodingProobjectsrecursioncsvdata-transformation
Not solved

Share this question

Problem

Exporting data to CSV, rendering it in a spreadsheet-like grid or comparing records side by side all need the same step: turn a list of (possibly nested) objects into a table. Write objectsToMatrix(items), which returns a 2-D array: a header row of column names, then one row per item.

objectsToMatrix([
  { b: 1, a: 2 },
  { b: 3, a: 4 },
]);
// [["a", "b"],
//  [2, 1],
//  [4, 3]]

objectsToMatrix([
  { name: "Asha", address: { city: "Pune", pin: 411001 } },
  { name: "Ravi", address: { city: "Delhi" }, admin: true },
]);
// [["address.city", "address.pin", "admin", "name"],
//  ["Pune", 411001, "", "Asha"],
//  ["Delhi", "", true, "Ravi"]]

Ref. UR-1431 · © UIRound · uiround.com/questions/turn-an-array-of-nested-objects-into-a-table-with-sorted-dotted-column-paths

Stuck? Take a hint

Try it in the editor

Run your code as often as you like. Submitting it to the full test suite is part of Pro.

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment