简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM