Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are square brackets needed to stringify all elements of a Map in Javascript?

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.

like image 955
Scott O'Toole Avatar asked Apr 22 '18 04:04

Scott O'Toole


People also ask

Why do we use square brackets in JavaScript?

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.

Why we use square brackets for array?

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.

What does square brackets mean in node JS?

Square brackets means new Array.

How do you Stringify a map?

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.


1 Answers

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.

like image 76
Ry- Avatar answered Oct 14 '22 00:10

Ry-