繁体   English   中英

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

[英]Node.js Storing JSON data in array for later use

我是使用 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
} 

暂无
暂无

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

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