Reputation: 326
Problem: I can't seem to find a satisfactory explanation of why javascript Maps need square brackets for the JSON.stringify method to "reach"(?) into the nested elements. I think I'm missing something about ES6, or something inherent to the Map data type.
I can convert the Map to an object, and stringify- but why is this extra step necessary?
My experiment:
const blah = new Map();
blah.set('u', {
'something': [{'hey':98}, 56, 'bob']
});
blah.set({
'hey': {'hey': 78}
}, 'what?');
console.log(JSON.stringify(...blah));
//["u",{}]
//I thought this would yield the result of the below console.log
console.log(JSON.stringify([...blah]))
//[["u",{"something":[{"hey":98},56,"bob"]}],[{"hey":{"hey":78}},"what?"]]
//Why are the square brackets needed to stringify and display each element of
//the map?
This article confirms the behavior, but doesn't explain why it happens.
Upvotes: 6
Views: 523
Reputation: 224904
JSON.stringify(...blah)
is argument spread, which takes the values you get when iterating over the map:
['u', {'something': …}]
[{'hey': …}, 'what?']
and passes them as distinct arguments to JSON.stringify
:
JSON.stringify(
['u', {'something': …}],
[{'hey': …}, 'what?']
);
The second argument to JSON.stringify
is supposed to be a replacer function. Since you’ve given it something that isn’t a function, it ignores that.
Argument spread is not remotely what you want. What you want is to convert the map to an array of key/value pairs, and that’s what [...blah]
does. Array.from(blah)
would have the same effect.
Upvotes: 4