Turn an array of nested objects into a table: dotted column paths, sorted headers and blanks for missing values
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
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 2
- code listings
- 5
- edge cases
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Flatten each item first: walk it recursively and record every leaf value under its path, with keys joined by '.'. Arrays are walked like objects, so their indexes become path parts.
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.