繁体   English   中英

如何在对象数组中打印项目

[英]How to print items in an object array

我从一个站点返回一个对象,该站点除其他参数外还包含对象数组。

如果我执行console.log(req.body.cart),则打印此[{标题:'iphone 6',成本:'650'}]

我只需要标题。 我尝试了stringify,这不是我想要的,然后解析返回500错误。

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);
});

我需要按标题显示项目

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

上面的作品,但有很多丑陋的数据,只需要项目的标题。

尝试这个。 '<p>Cart: ' + JSON.parse(req.body.cart).title + '</p>'

如果购物车中有多个物品,则可以迭代这些物品,否则可以直接访问它req.body.cart[0].title

var cart = req.body.cart;

var 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>';

 html +=  '<p>Cart:<ul> '+

for(var i=0;i<cart.length;i++) html +='<li> ' + cart[i].title + '</li>';

html +='</ul></p>';

  var cart = [ { title: 'iphone 6', cost: '650' }, { title: 'iphone 5', cost: '550' } ]; document.write( '<p>Cart:<ul> '); for(var i=0;i<cart.length;i++) document.write('<li> ' + cart[i].title + '</li>'); document.write('</ul></p>'); 

如评论中所建议:

'<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>'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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