0

I am iterating through a json object and it fails due to an extra element.

see code bellow

{
"rootLayout":"main",
"layoutDescriptions":[
      {
        "type":"Panel",
        "label":"Repeating Groups By Subform",
        "layout":"SimpleForm",
        "content":[
          { "type":"label", "constraint":"newline", "text":"Contacts" },
          { "type":"repeatableGroup", "property":"contacts", "contentRef":"ContactSubForm" }
        ]
      },
      {
        "type":"Panel",
        "label":"",
        "container" : {
          "type":"Panel",
          "layout":"SimpleForm",
          "content":[
            { "type":"label", "constraint":"newline", "text":"Contact Name" },
            { "type":"ListView", "property":"contactName", "listProps":["contactName","telephone","email"] }
          ]
        }
      },

it fails on the second element in the array I am using the following to get my results

data.layoutDescriptions[0].container.content[i].content

I know its stopping because on

data.layoutDescriptions[0].container.content[1].content

it expects

data.layoutDescriptions[0].container.content[1].container.content

so my question is how do I say if container is present do this else do this.

I am trying this at the moment which does not work.

    var contentObjects = data.layoutDescriptions[0].container.content[1].content;
if(contentObjects.container){
                 alert("container exists");
                 }
                         else{
                  alert("nope");
                  }

Thanks.

Sagarmichael
  • 1,624
  • 7
  • 24
  • 53
  • So, actually your question has nothing to do with JSON, only how to test the existence of properties of JavaScript objects? – Felix Kling Aug 08 '12 at 15:24
  • possible duplicate of [javascript test for existence of nested object key](http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key) – Felix Kling Aug 08 '12 at 15:25

2 Answers2

1

The issue is that not every object inside the array layoutDescriptions has the attribute container. When you loop over the first object, it looks for container, doesn't find anything, and then searches for content on undefined, throwing an error.

Also, inside data.layoutDescriptions[0].container.content[1], you don't have a content attribute. contentObjects gets set to undefined and therefore contentObjects.container will fail.

Brian Ustas
  • 62,713
  • 3
  • 28
  • 21
1

use hasOwnProperty to check if an object has its own property exists:

 var contentObjects = data.layoutDescriptions[0].container.content[1];
 if(contentObjects.hasOwnProperty('container'){
     alert("container exists");
 }
 else{
     alert("nope");
 }
Evan
  • 5,975
  • 8
  • 34
  • 63