ash123
ash123

Reputation: 307

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.

Upvotes: 7

Views: 17458

Answers (3)

Krease
Krease

Reputation: 16215

The other answers are good if you have no control over the return format.

However, if you can, I'd recommend changing the return format to put the important values you care about as actual values instead of keys to make it clearer. For example, something like this:

result = 
{
  "name: "myArray",
  "value": [
    {
      "version": 5,
      "permissionMask": 1
    },
    {
      "version": 126,
      "permissionMask": 1
    }
  ]
}

Then, it's a lot clearer to reliably access the property you care about: result.name

Upvotes: 0

elixenide
elixenide

Reputation: 44833

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.

Upvotes: 7

Amadan
Amadan

Reputation: 198314

Object.keys(data)[0]
# => "myArray"

A terminology note: This solution assumes you have a JavaScript object. You might have a JSON string, in which case this is the solution:

Object.keys(JSON.parse(data))[0]
# => "myArray"

However, "JSON object", in JavaScript, is just one - the one I used just now, that has JSON.parse and JSON.stringify methods. What you have is not a JSON object except perhaps in a trivial interpretation of the second case, where all values in JavaScript are objects, including strings.

Upvotes: 4

Related Questions