Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index value of Array

Tags:

json

I have a json file with contents like this:

{
     "aaa":{
         "status":"available",
         "classkey":"dotnet"
     },
     "bbb":{
         "ccc":{
             "com":"available",
             "net":"available",
             "info":"available",
             "org":"available"
          }
     }
}

Now I want to fetch the value of array by index (ex., xxx[0] like this not like xxx['aaa']). How do I do that?

like image 478
ashu Avatar asked Nov 20 '10 05:11

ashu


People also ask

What is the index of an array?

The index indicates the position of the element within the array (starting from 1) and is either a number or a field containing a number.

How do you find the index of an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

What is index in array example?

An array is an ordered list of values that you refer to with a name and an index. For example, consider an array called emp , which contains employees' names indexed by their numerical employee number. So emp[0] would be employee number zero, emp[1] employee number one, and so on.

How do you find the index value of an array of objects?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.


2 Answers

You can't. Order is not guaranteed in json and most other key-value data structures. Furthermore you don't have an array, you have an object. Why use name-value pairs at all if you aren't going to use the names to access the values? Therein lies the power of json and other key-value data stores. If you need to access the values by integer indexes, then just use an array to store your data.

like image 195
Alex Avatar answered Sep 27 '22 21:09

Alex


Actually you can use int index like an array in JSON, just try that:

var jsonObject = {
     "0":{
         "status":"available",
         "classkey":"dotnet"
     },
     "1":{
         "ccc":{
             "com":"available",
             "net":"available",
             "info":"available",
             "org":"available"
          }
     }
}

alert(jsonObject[0].status)
like image 36
Xdevelop Avatar answered Sep 27 '22 21:09

Xdevelop