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.
The [] operator converts the expression inside the square brackets to a string. For instance, if it is a numeric value, JavaScript converts it to a string and then uses that string as the property name, similar to the square bracket notation of objects to access their properties.
They are used with many different things including classes, functions, loops, and conditionals. Square brackets are used to index (access) elements in arrays and also Strings. Specifically lost[i] will evaluate to the ith item in the array named lost.
Square brackets means new Array.
To convert a map to JSON string in JavaScript, convert map to JavaScript object using Object. fromEntries() and then pass this object as argument to JSON. stringify() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With