Say I have data in a JSON object formatted similar to...
{"data":
[["X","Y","Z"],
["52","23","10"],
["46","65","32"]]
}
So essentially, each row takes the form [X, Y, Z]
.
What would be the easiest way to then access an entire "column" or vector of data? For example, let's assume the "X", "Y", and "Z" is a header row, and I want to access all of the "X" data.
Do I need to iterate over the entire object somehow to retrieve the first member of each element, which would correspond to the "X" column?
I'd like to do this in JavaScript if possible.
Thanks much for any assistance!
Try below sample code that is simple and straight forward to access the first column.
First iterate the first row to find the correct column then get the values of that column for next rows.
<script type="text/javascript">
var obj = {
"data" : [
[ "X", "Y", "Z" ],
[ "52", "23", "10" ],
[ "46", "65", "32" ]
]
};
var column;
for (var i = 0, j = obj.data.length; i < j; i++) {
if (obj.data[0][i] === 'X') {
column = i;
break;
}
}
for (var i = 1, j = obj.data.length; i < j; i++) {
var val = obj.data[i][column];
console.log(val);
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With