Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use res.send() return Set or Map Object

[email protected]

router.get('/set-object', async (req, res) => {
    let a = new Set([1, 2, 3]);
    let b = new Map();
    b.set('hello', 'world')
    res.send({a: a, b: b});
})

but I get result:

{
    "a": {},
    "b": {}
}

why res.send() or res.json() Set or Map is {}

like image 297
Borkes Avatar asked Apr 10 '18 08:04

Borkes


1 Answers

res is sending JSON, but Set and Map are structures (types) that store data, so you need to convert them to JSON-compatible types before sending as a response. Use Array.from function or spread operator like this:

res.send({a: Array.from(a), b: Array.from(b)}); // You might need a more complex logic for mapping b
// OR
res.send({a: [...a], b: [...b]});
like image 185
Anna Tolochko Avatar answered Oct 01 '22 12:10

Anna Tolochko