Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading