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?

3
  • Possible duplicate of Iterate through object properties Commented May 26, 2016 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. Commented May 26, 2016 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. Commented May 26, 2016 at 16:49

3 Answers 3

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

2 Comments

Perfect! This worked 100%. I am a bit new to nested JSON and properties! Thank you again @nikhil
@chrisrhyno2003 - Happy to help you
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]);
   }
}

Comments

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 : 

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.