Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the name of the array in json data using JavaScript

I have a JSON object which comes back like this from a JavaScript API call:

{
  "myArray": [
    {
      "version": 5,
      "permissionMask": 1
    },
    {
      "version": 126,
      "permissionMask": 1
    }
  ]
}

How can I access the name of the array (i.e myArray) in JavaScript. I need to use the name of the array to determine the flow later on.

like image 514
ash123 Avatar asked May 12 '15 00:05

ash123


1 Answers

Use getOwnPropertyNames to get a list of the properties of the object in array form.

Example:

var myObj = {
  "myArray": [
    {
      "version": 5,
      "permissionMask": 1

    },
    {
      "version": 126,
      "permissionMask": 1

    }
  ]
},
names = Object.getOwnPropertyNames(myObj);
alert(names[0]); // alerts "myArray"

Note: If the object can have more than one property, like myArray, myInt, and myOtherArray, then you will need to loop over the results of getOwnPropertyNames. You would also need to do type-testing, as in if(names[0] instanceof Array) {...} to check the property type. Based on your example in your question, I have not fleshed all of that out here.

like image 130
elixenide Avatar answered Sep 17 '22 21:09

elixenide