Node.js将JSON数据存储在数组中以备将来使用

Node.js Storing JSON data in array for later use

本文关键字:将来 数组 js JSON 数据 存储 Node      更新时间:2024-02-28

我刚开始使用JSON。我有一个for循环,如下所示,每次执行都返回不同的product(具有不同的owner_idname字段)

for (/* some condition here */) {
    product = {
         owner_id: somevalue,
         name: somevalue
    }
}

我需要存储所有不同出现的product,以便以后使用。我正在考虑使用数组,所以我将上面的代码改为:

var selectedProducts = [];
for (/* some condition here */) {
    product = {
         owner_id: somevalue,
         name: somevalue
    }
    selectedProducts.push(product);
    selectedProducts.push(JSON.stringify(product));
}

但我得到的是一个包含undefined内容的数组。

稍后我需要实现的是调用如下那样的for循环

for(var i = 0; i < selectedProducts.length; i++) {
    console.log(selectedProducts[i]); // Will print the single JSON object
}

我怎样才能达到这样的结果?

您可以将selectedProducts数组存储在会话中(请参阅文档)。

var selectedProducts = [];
for (/* some condition here */) {
    product = {
         owner_id: somevalue,
         name: somevalue
    }
    selectedProducts.push(product);
}
req.session.selectedProducts = selectedProducts;

然后从会话中取回数组。

for(var i = 0; i < req.session.selectedProducts.length; i++) {
    console.log(req.session.selectedProducts[i]); // Will print the single JSON object
}