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 Commented Jul 6, 2015 at 20:05

4 Answers 4

28
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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

what exactly should print ? I got 'undefined', twice :(
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 Comment

for..in is for looping over keys of Objects, you may want to loop using for instead
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]);
};

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.