Search code examples
javascriptdictionaryobject

How can I convert an arbitrarily deep nested object to a similarly nested Map?


I am trying to convert an arbitrarily deep nested object to a similarly nested Map.

const exampleInput = { a: 1, b: { c: 2, d: { e: 3 } } };
const expectedOutput = new Map([['a', 1], ['b', new Map([['c', 2], ['d', new Map([['e', 3]])]])]]);
const nestedObj2Map = (o, m = new Map()) => {
  for (const [k, v] of Object.entries(o)) {
    if (typeof (v) === 'object' && v !== null) {
      m.set(k, nestedObj2Map(v, m));
    } else m.set(k, v);
  }
  return m;
};
nestedObj2Map(exampleInput);

When I run it in Chrome console, it returns a nested Map with too many entries. Can anyone see a way to achieve this goal?


Solution

  • The problem is on this line:

    m.set(k, nestedObj2Map(v, m));
    

    You're passing the map recursively. Removing m from the passed parameters will work.

    Your code will be like this:

    const exampleInput = { a: 1, b: { c: 2, d: { e: 3 } } };
    const expectedOutput = new Map([['a', 1], ['b', new Map([['c', 2], ['d', new Map([['e', 3]])]])]]);
    const nestedObj2Map = (o, m = new Map()) => {
      for (const [k, v] of Object.entries(o)) {
        if (typeof (v) === 'object' && v !== null) {
          m.set(k, nestedObj2Map(v)); // removed m from the parameters
        } else m.set(k, v);
      }
      return m;
    };
    nestedObj2Map(exampleInput);
    

    The reason the previous implementation doesn't work is that you want each level of nesting to have its own Map, but when you pass the previous map as a parameter, each recursive call will actually just modify the initial map instead of creating a new one.