15

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.

1
  • JSON is just a notation. Convert it into a native Array and then perform the operation as usual, for(;;) for an Array, for..in for an Object
    – Paul S.
    Jul 6, 2015 at 20:05

4 Answers 4

27
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);
});
1
  • what exactly should print ? I got 'undefined', twice :(
    – Ariadne R.
    Dec 23, 2020 at 12:34
11

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;
}
1
  • for..in is for looping over keys of Objects, you may want to loop using for instead
    – Paul S.
    Jul 6, 2015 at 20:06
1

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.