-3

So I have this array of JSON objects:

[
  {
    "columns": [
      {
        "fields": [
          {
            "valueFields": [
              {
                "type": 1,
                "fieldName": "prj_Name",
                "value": "1A BNL FB e-Powedr basic Balci Reizen",
                "valueId": "",
                "defaultValue": false,
                "baseValue": false,
                "mandatoryField": true,
                "hasError": false,
                "errorMessage": "",
                "disabled": false,
                "visible": true
              }
            ]
          }
        ]
      }
    ]
  }
]

and I would like to Iterate through the Data to do some stuff with it later.

I already tried this :

for (var key in currentObject) {
    if (currentObject.hasOwnProperty(key)) {
        console.log(key + ': ' + currentObject[key]);
    }
}

But it prints every letter separatly in the console, so I guess it isn't right. Do you have any Ideas of what I am doing wrong ?

[EDIT]

I tried to add var currentObject = JSON.parse(Json); before the for loop.

I now get this printed 0: [object Object]

How to iterate through the object then ?

Miroslav Saracevic
  • 1,446
  • 1
  • 13
  • 32
Darkpingouin
  • 196
  • 12

1 Answers1

1

Your JsonObject is a JsonArray in a JsonArray in a JsonArray in a JsonArray...

Try the following code online, it works for your case

var x  = '[{"columns":[{"fields":[{"valueFields":[{"type":1,"fieldName":"prj_Name","value":"1A BNL FB e-Powedr basic BalciReizen","valueId":"","defaultValue":false,"baseValue":false,"mandatoryField":true,"hasError":false,"errorMessage":"","disabled":false,"visible":true}]}]}]}]';
var parsedJson = JSON.parse(x);
var valueFields = parsedJson[0].columns[0].fields[0].valueFields[0];

for (var key in valueFields) {
    if (valueFields.hasOwnProperty(key)) {
        console.log(key + ': ' + valueFields[key]);
    }
}

I would suggest to change the output if it's only one result to make it easier to parse. If you have access to modify the server code ofcourse.

Denny
  • 1,766
  • 3
  • 17
  • 37
  • This is the simpliest reauest I had to show you. In some cases It could happen that I get multiple columns with multiple fields having multiple valuefields in it. – Darkpingouin Jun 08 '17 at 09:56
  • So I guess I should add `foreach` loop to iterate through each Array of the Object. Thx a lot for your help. – Darkpingouin Jun 08 '17 at 09:57
  • You have to make multiple loops if you want to handle your main json, `columns`, `fields` and `valueFields`. – Denny Jun 08 '17 at 09:57