Skip to content
Advertisement

How to print a nest list of map with Javascript

I have a function which converts a set of Javascript objects into a map. However, I get an object which cannot be navigated for its values; Here is the sample json

JavaScript

Here is my function to convert to a map:

JavaScript

Here is how I try to use and print the map:

JavaScript

However, I get for some this key, salesIndex, [object Map], why are the key, values not printed?

Advertisement

Answer

why are the key, values not printed?

They are printed, but the primitive values only get printed (later) when the object is passed to the recursive call, and there the else block is executed, i.e. when you arrive at the base case of the recursion.

Your code is fine, but you should avoid printing the value when you’re not yet at that base case, as that value still needs to be passed to the recursive call, which will take care of printing the deeper key/values.

I would suggest:

  • To only print the key (not the value) when the value is still an object
  • Print with indentation so it is much clearer what the structure is of the data
  • In objectToMap, support null values: for that you need to change the is-object test.

That’s the most important, but I’d also:

  • In objectToMap, use Object.entries instead of Object.keys so you get both the key and the value as your loop variables
  • Similarly, in printMap, use map.entries instead of map.values so you get both the key and the value as your loop variables
  • In objectToMap, as you call map.set() in both if and else cases, start with the call, and differentiate the argument with a conditional (ternary) operator

So like this:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement