0

I have a nested json which looks like this:

{'services': 
    {
        'serviceA': 'OptionA',
        'serviceB': 'OptionB',
        'serviceC': null
    },
'AttributeB': 'ValueB',
'AttributeC': 'ValueC'
}

I would like to render nested json (services) in a tabular format like this:

services option serviceA OptionA serviceB OptionB serviceC

I was trying something like this:

var myJSONObject =  {'services': 
        {
            'serviceA': 'OptionA',
            'serviceB': 'OptionB',
            'serviceC': null
        },
    'AttributeB': 'ValueB',
    'AttributeC': 'ValueC'
    };

for(var i = 0; i < myJSONObject.services.length; i++)
{
    var product = myJSONObject.services[i];
    alert(product.key);
    alert(product.value);
}

This doesn't seem to help. I am guessing I am retrieving the object in an incorrect manner. Can somebody help?

chrisrhyno2003
  • 3,906
  • 8
  • 53
  • 102
  • Possible duplicate of [Iterate through object properties](http://stackoverflow.com/questions/8312459/iterate-through-object-properties) – jeffjenx May 26 '16 at 16:48
  • When you type product.key, are you actually typing product.AttributeB? Also, use console.log() to see what the values are of things you're printing. – ale10ander May 26 '16 at 16:48
  • You are iterating over an object but using the array syntax. Use the `for in` loop to iterate over the object instead of `for` loop. – TeaCoder May 26 '16 at 16:49

3 Answers3

3

services is an object and you need to iterate over its properties. For that you can try following

var myJSONObject =  {'services': 
        {
            'serviceA': 'OptionA',
            'serviceB': 'OptionB',
            'serviceC': null
        },
    'AttributeB': 'ValueB',
    'AttributeC': 'ValueC'
    };

for(var key in myJSONObject.services)
{
    alert(key);
    alert(myJSONObject.services[key]);
}
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

@nikhil's answer works but you might want to check for properties using hasOwnProperty also to be on the safe side.

let services = myJSONObject.services
for(let key in services)
{
   if(services.hasOwnProperty(key)) {
     console.log(key);
     console.log(services[key]);
   }
}
TeaCoder
  • 1,958
  • 13
  • 13
0

Short solution using Object.keys and Array.forEach functions:

var services = myJSONObject['services'];
Object.keys(services).forEach((key) => console.log(key + ' : '+ (services[key] || "")));

The output:

serviceA : OptionA
serviceB : OptionB
serviceC : 
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105