map2tree

4.0.0 · active · verified Sun Apr 19

map2tree is a utility library that provides a pure function to convert a flat map structure into a hierarchical tree. Its primary use case is within the `redux-devtools-chart-monitor` package, influencing its specific opinions on how data is transformed. It does not convert objects and arrays deeply nested within collections into tree structures and offers support for Immutable.js List and Map data types. The current stable version, 4.0.0, was released as an ESM-only package. The library is part of the `reduxjs/redux-devtools` monorepo, suggesting its release cadence is tied to the broader Redux DevTools ecosystem.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and use `map2tree` with a sample map, specifying root key and child order, and logs the resulting tree structure.

import map2tree from 'map2tree';

const someMap = {
  someReducer: {
    todos: [
      { title: 'map', someNestedObject: { foo: 'bar' } },
      { title: 'to', someNestedArray: ['foo', 'bar'] },
      { title: 'tree' },
      { title: 'map2tree' },
    ],
    completedCount: 1,
  },
  otherReducer: {
    foo: 0,
    bar: { key: 'value' },
  },
};

const treeOutput = map2tree(someMap, {
  key: 'state', // the name you want for the root node of the output tree
  pushMethod: 'push', // use 'unshift' to change the order children nodes are added
});

console.log(JSON.stringify(treeOutput, null, 2));
/*
Output example:
{
  "name": "state",
  "children": [
    {
      "name": "someReducer",
      "children": [
        {
          "name": "todos",
          "children": [
            {
              "name": "todo[0]",
              "object": {
                "title": "map",
                "someNestedObject": {
                  "foo": "bar"
                }
              }
            },
            {
              "name": "todo[1]",
              "object": {
                "title": "to",
                "someNestedArray": [
                  "foo",
                  "bar"
                ]
              }
            },
            {
              "name": "todo[2]",
              "object": {
                "title": "tree"
              }
            },
            {
              "name": "todo[3]",
              "object": {
                "title": "map2tree"
              }
            }
          ]
        },
        {
          "name": "completedCount",
          "value": 1
        }
      ]
    },
    {
      "name": "otherReducer",
      "children": [
        {
          "name": "foo",
          "value": 0
        },
        {
          "name": "bar",
          "object": {
            "key": "value"
          }
        }
      ]
    }
  ]
}
*/

view raw JSON →