0

I have a Json array which has the elements below: "adjacencies", "data", "id", "name". In some elements, "adjacencies" does not exist. This is an example:

var JsonArray = [
                 {
                   "id" : "id1",
                   "name" : "name1",
                   "data" : {
                             "$type" : "circle",
                             "$color" : "#AEC43B"
                            }
                 }, //Without "adjacencies"

                 {
                   "id" : "id2",
                   "name" : "name2",
                   "data" : {
                             "$type" : "circle",
                             "$color" : "#AEC43B"
                            }
                 }, //Without "adjacencies"

                 {
                    "adjacencies": [
                                    {
                                     "nodeTo": "id1",
                                     "nodeFrom": "id3",
                                     "data": {
                                              "$color": "#416D9C"
                                             }
                                    }
                                    ],
                    "id" : "id3",
                    "name" : "name3",
                    "data" : {
                             "$type" : "circle",
                             "$color" : "#AEC43B"
                            }
                 } //With "adjacencies"
                ];

The first and the second elements doesn't contain "adjacencies", but the third element does. In the loop for (i = 0; i < JsonArray.length; i++) how do I access the third element? Is there a .contain property for example? Thanks in advance:)

2
  • 1
    use the in operator, e.g. 'property' in obj // returns a boolean Commented Sep 24, 2012 at 8:13
  • But be careful when using "in" for objects as it will also iterate through prototype's properties. Commented Sep 24, 2012 at 8:16

2 Answers 2

2

One way to do it is by checking if the value is of type undefined:

for (i = 0; i < JsonArray.length; i++) {
    var item = JsonArray[i];
    if (typeof item.adjacencies !== "undefined") {
        // item has adjacencies property
    }
}

As an aside: this is not a JSON array -- it's a Javascript array. There are no JSON objects, no JSON arrays, no JSON nothing. The only JSON-y thing that exists is plain JSON, which is a serialization format.

Sign up to request clarification or add additional context in comments.

Comments

0

use hasOwnProperty

So you can do this

for (i = 0; i < JsonArray.length; i++){
    if( JsonArray[i].hasOwnProperty('adjacencies') ){
        //Do something here
    }
}

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.