traveller traveller - 6 months ago 9
Node.js Question

How to print items in an object array

I am returning an object from a site which apart from other parameters also contains an array of objects.

If I do console.log(req.body.cart) I print this [ { title: 'iphone 6', cost: '650' } ]

which I need only the title. I tried stringify, which is not what I want and parse which returned an 500 error.

router.post('/itemstobuy', function(req, res, next){
if(!req.body.name || !req.body.lastname || !req.body.address
|| !req.body.email || !req.body.cart){
return res.status(400).json({message: 'Please fill out all fields'});
}

var mailOptions={
from: 'anEmail@gmail.com',
to: 'anotherEmail@gmail.com',
subject: 'Subject',
html: '<p>Name: ' + req.body.name + '</p>' +
'<p>LastName: ' + req.body.lastname + '</p>' +
'<p>Address: ' + req.body.address + '</p>' +
'<p>Email: ' + req.body.email + '</p>' +
'<p>Cart: ' + JSON.stringify(req.body.cart) + '</p>'
}

transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});

return res.status(200);
});


I need to show the items by their title at

'<p>Cart: ' + JSON.stringify(req.body.cart) + '</p>'


The above works but there are lots of ugly data and need just the titles of the items.

Answer

As suggested in the comments:

'<p>Cart: ' + 
 (req.body.cart || []) //Just to make things not crash and burn if we have no cart
     //Take the title from each of the items
     .map(function(item){ return item.title; })
     //Create a comma-separated string from the titles
     .join(', ') + 
'</p>'
Comments