简体   繁体   English

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

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

I am pretty new working with JSON.我是使用 JSON 的新手。 I have a for loop like the following that everytime is executed returns a different product (with different owner_id and name fields)我有一个如下所示的 for 循环,每次执行都会返回不同的product (具有不同的owner_idname字段)

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

I need to store all the different occurrences of product for a later use.我需要存储所有不同的product以供以后使用。 I was thinking about using an array, so I changed the above code to this:我正在考虑使用数组,所以我将上面的代码更改为:

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

But what I get is an array with undefined content.但我得到的是一个内容undefined的数组。

What I need to achieve later is calling a for cycle like the following我稍后需要实现的是调用如下所示的 for 循环

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

How can I achieve such a result?我怎样才能达到这样的结果?

You could store the selectedProducts array on the session (see docs ).您可以在会话中存储selectedProducts数组(请参阅文档)。

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

req.session.selectedProducts = selectedProducts;

Then get the array back from the session.然后从会话中取回数组。

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