Javascript 如何迭代 Node.js 中的 JSON 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31254578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:26:30  来源:igfitidea点击:

How to iterate over a JSON array in Node.js?

javascriptnode.jsjson

提问by Piet

I have a JSON array:

我有一个 JSON 数组:

[
    {
        "art": "A",
        "count": "0",
        "name": "name1",
        "ean": "802.0079.127",
        "marker": "null",
        "stammkost": "A",
        "tablename": "IWEO_IWBB_01062015"
    },
    {
        "art": "A",
        "count": "0",
        "name": "2",
        "ean": "657.7406.559",
        "marker": "null",
        "stammkost": "A",
        "tablename": "IWEO_IWBB_02062015"
    }
]

To iterate over the array in PHP I would use the following code to iterate over the tablenames:

要在 PHP 中遍历数组,我将使用以下代码来遍历表名:

foreach($jArray as $value){ 
  $tablename = $value['tablename'];
  //some code
}

How can I do this in Node.js? I found many questions with it, but no actual answer. Most of them are from 2011.

我怎样才能在 Node.js 中做到这一点?我发现了很多问题,但没有实际答案。其中大部分是2011年的。

回答by Clarkie

var tables = [
    { "art":"A","count":"0","name":"name1","ean":"802.0079.127","marker":"null","stammkost":"A","tablename":"IWEO_IWBB_01062015" },
    { "art":"A","count":"0","name":"2","ean":"657.7406.559","marker":"null","stammkost":"A","tablename":"IWEO_IWBB_02062015" }
];

tables.forEach(function(table) {
    var tableName = table.name;
    console.log(tableName);
});

回答by tier1

You need to de-serialize it to an object first.

您需要先将其反序列化为一个对象。

var arr = JSON.parse(<your json array>);
for(var i = 0; i < arr.length; i++)
{
  var tablename = arr[i].tablename;
}

回答by Sai Jeevan Balla

var tables = [
    { "art":"A","count":"0","name":"name1","ean":"802.0079.127","marker":"null","stammkost":"A","tablename":"IWEO_IWBB_01062015" },
    { "art":"A","count":"0","name":"2","ean":"657.7406.559","marker":"null","stammkost":"A","tablename":"IWEO_IWBB_02062015" }
];

tables.map(({name})=> console.log(name)) 

for iterate in js for...in, map, forEach, reduce

在 js 中迭代 for...in、map、forEach、reduce

回答by ROOT

Another way to iterate over Array in node:

在节点中迭代数组的另一种方法:

let Arr = [
    {"art": "A","count": "0","name": "name1","ean": "802.0079.127","marker": "null","stammkost": "A","tablename": "IWEO_IWBB_01062015"},
    {"art": "A","count": "0","name": "2","ean": "657.7406.559","marker": "null","stammkost": "A","tablename": "IWEO_IWBB_02062015"}
];

for (key in Arr) {
  console.log(Arr[key]);
};