【问题标题】:How to get specific value using node js如何使用节点 js 获取特定值
【发布时间】:2021-04-20 19:27:36
【问题描述】:

如何从findAll()返回的对象中提取属性name 因为我想要所有存在于我的数据库中但获得undefined 值的名称

function checkDoc(childProduct) {
  return new Promise((resolve, reject) => {
    Document.findAll({
      raw:true,
      where: {
        product_id: childProduct.id,
      },
    })
      .then((productDoc) => {
        console.log(productDoc);
      })
      .catch(function (err) {
        return reject(
          getFailureResponseJson("Can't be added please try again :) " + err)
        );
      });
  });
}

输出自:console.log(product);

{
id: 01,
name: ABC,
description: demo,
}
{
id: 02,
name: PQR,
description: demo,
}
{
id: 03,
name: XYZ,
description: demo,
}

我正在使用 console.log(product.name),但它显示的是 undefined - 我如何才能获得名称?

【问题讨论】:

  • 试试console.log(product['name'])console.log(product[0].name)
  • console.log(product[0].name) 应该可以工作,您正在尝试访问产品数组的名称,这是未定义的
  • @tomichel 没错!

标签: node.js promise sequelize.js nodes


【解决方案1】:

尝试在产品上使用 foreach 循环:

productDoc.forEach((singleProduct) => {
   console.log('Product Name: ', singleProduct.name)
});

或者简单地说:

console.log('Product Name: ', productDoc[0].name)
// where '0' is the index of first product

也许你得到的是一组对象,而不是一个对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多