Piet
Piet

Reputation: 415

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

I have a JSON array:

[
    {
        "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:

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.

Upvotes: 15

Views: 51021

Answers (4)

ROOT
ROOT

Reputation: 11622

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]);
};

Upvotes: 1

Sai Jeevan Balla
Sai Jeevan Balla

Reputation: 145

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

Upvotes: 0

Clarkie
Clarkie

Reputation: 7550

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);
});

Upvotes: 27

tier1
tier1

Reputation: 6433

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;
}

Upvotes: 11

Related Questions