I have two dimensional JSON array. I can take data from first dimension like data["dimension-1"] however i cannot take data from second dimension like: data["dimension-1"]["dimension-2"]. What is the proper way to take single row from second dimension of my array?
-
Show us your JSON Array please :)Luka Jacobowitz– Luka Jacobowitz2016-04-03 11:18:18 +00:00Commented Apr 3, 2016 at 11:18
-
Definitely you should show your array here because data["dimension-1"] accesses a property not an array - so my answer may have been a waste of time.chriskelly– chriskelly2016-04-03 11:30:20 +00:00Commented Apr 3, 2016 at 11:30
-
Here is my JSON: pastebin.com/BGxK4f39 I want to get into value of id propertyJakub Pastuszuk– Jakub Pastuszuk2016-04-03 11:45:35 +00:00Commented Apr 3, 2016 at 11:45
3 Answers
data["dimension-1"]["dimension-2"] - seems to be rather an object - hence it should look like :
var data = {
"dimension-1" : {
"dimension-2" : 'value'
}
}
data["dimension-1"]["dimension-2"] // will display 'value'
and then your way it ok.
but if it's an array
var data =[[1,2], [3,4]]
then one should access it like (the indexes are NUMERIC - not strings or any other):
data[0][1] // will display 2
Comments
You have an object with properties that are also a mixture of arrays or objects. If you are trying to extract the ID of the data property, which is an array, then you will need to select the property, enter the array (first item is 0), which returns another object. Then just select the property.
You'll need something like the following in your use case: -
objectName.data[0].id
or
objectName["data"][0]["id"];
This is for extracting the ID from within the data attribute in data like this (that you provided): -
var objectName = {
"total_pages": 1424,
"total_rows": 1424,
"data": [
{
"id": 1525,
"television_id": 1,
// other stuff
"categories": [
{
"id": 170,
"title": "title"
},
{
"id": 4,
"title": "message"
}
]
}
]
}
Comments
A 2 dimensional JSON array looks like this:
[
["a", "b", "c"],
["d", "e", "f"],
["g", "h", "i"]
]
Say you want to access the last column in the second column. i.e. "f", then you need to access it by number not name. i.e.:
data[1][2]
EDIT:
Stictly speaking, my original answer is correct. Your 2 dimensional array may be accessed by indices.
However, knowing the format of your data now, I would recommend either:
Use a library (e.g. lodash) to give you simple and expressive ways to query your data
or create your own function. e.g.:
var category = getCategory(x.data, 1525, 170);
function getCategory(data, id, catId) {
return data
.filter(d => d.id === id)
.map(d => d.categories
.filter(c => c.id === catId)
.map(c => c.title)
.shift()
)
.shift()
}
Good luck!