【问题标题】:NodeJS API get Items array of items pro each categoryNodeJS API 获取每个类别的 Items 项目数组
【发布时间】:2020-05-22 00:58:32
【问题描述】:

早安,

您能否建议如何为每个类别创建仅属于该类别的项目列表,如下所示:

[
    {
        "id": category1,
        "name": "Category1",
        "products": [
            {
                "id": product1,
                "name": product1.name
                "images": [
                    {
                        "id": product1,
                        "url": product1.img,

                    },

        ]
        },
        {
        "id": category2,
        "name": "Category2",
        "products": [
            {
                "id": product2,
                "name": product.name
                "images": [
                    {
                        "id": product2,
                        "url": product2.img,
                    }]
            },
            {
                "id": product3,
                "name": product3.name
                "images": [
                    {
                        "id": product3,
                        "url": product3.img,
                    }]
            }      
        ]
    }
]

这是对数据库的请求:

connection.query("SELECT productId, productName, productImg, productCategoryId, ProductCategoryName FROM Items", function (err, tmpres) { }

if (err) {
    console.log("query failed!" + err);
    return res.json(500, err);
}

var data = [];

tmpres.forEach(function (a) {
    data.push({
        id: a.productCategoryId,
        title: a.productName
        ....
});

res.json(data);

提前致谢!

【问题讨论】:

  • 您有语法错误。你立即关闭你的回调函数function (err, tmpres) { }

标签: javascript mysql node.js api


【解决方案1】:

可以创建该数组,但是当您的列表增长时,这可能会出现性能问题。

我有一个替代方法,使用对象而不是数组。

 var data = {};

tmpres.forEach(function(a) {
  if (data[a.productCategoryId]) {
    data[a.productCategoryId].products.push({
      productId: a.productId,
      productName: a.productName,
      productImg: a.productImg
    });
  } else {
    data[a.productCategoryId] = {
      id: a.productCategoryId,
      title: a.productName,
      products: [
        {
          productId: a.productId,
          productName: a.productName,
          productImg: a.productImg
        }
      ]
    };
  }
});


// loop data

for (var key of Object.keys(data)) {
  console.log("id: " + key + " -> " + data[key].products) // productCategoryId and array of products
}

如果不需要使用数组,也可以。

【讨论】:

    猜你喜欢
    • 2018-12-04
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多