0

I'm trying to return an array and a map from my NodeJS request.

let returnData = {
    credits: [],
    details: new Map()
}
const data = req.body.data || req.body;
const credits = await CheckRegister.getReconcileCredits({
    propertyID: data.propertyID,
});
returnData.credits = credits;
for(const c of credits) {
    const paymentDetails = await TenantTransactions.getPaymentDetails(parseInt(c.CheckRegisterID));
    let description = '';
    for(const pd of paymentDetails) {
        description += `Tenant: ${pd.tenantFName} ${pd.tenantLName} .&nbsp;&nbsp;&nbsp;&nbsp;Amount: $${parseFloat(pd.TransactionAmount).toFixed(2)}<br/>`;
        returnData.details.set(parseInt(c.CheckRegisterID), description);
    }
}
return res.json(returnData);

When I check it in postman, the array data is returned, but the map is an empty object. However, when I console.log() the map before returning, it is a valid map with data.

0

1 Answer 1

2

Returning Map object is not enough. It's required to convert Map to valid json.

returnData.details = Object.fromEntries(returnData.details)
return res.json(returnData)
1
  • This works like a charm! However, if one has map with values like '4': 10, '2': 5, '3': 2, it will reorder it when transformed as object. The result will be '2': 5, '3': 2, '4': 10. This is due to the automatic order of the objects in js when the property/key is numeric-like value... If one add a prefix, it will keep the initial order.
    – VitoCK
    Commented Jun 9, 2023 at 14:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.