Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a JSON object to get column data

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!

like image 462
JoshG Avatar asked Sep 29 '22 06:09

JoshG


1 Answers

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>
like image 133
Braj Avatar answered Oct 01 '22 19:10

Braj