Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of elements inside of a JSON string [duplicate]

I have a JSON string that represents a datatable with one row. Here's the table:

"MyData":[
    {
        "FirstName":"John",
        "LastName":"Doe",
        "ID":1234,
        "QCR3m":null,
        "FR3m":null,
        "ERI3m":null,
        "QCR6m":null,
        "FR6m":null,
        "ERI6m":null,
        "QCR1y":90.05,
        "FR1y":null,
        "ERI1y":93.55,
        "QCR3y":93.51,
        "FR3y":95.86,
        "ERI3y":94.0,
        "QCR5y":93.25,
        "FR5y":95.86,
        "ERI5y":94.0
    }
]

I want to count the number of columns in MyData. In this case the number would be 18. Is this possible to do in javascript?

like image 747
joelforsyth Avatar asked Dec 14 '25 06:12

joelforsyth


1 Answers

Use Object.keys with length

var obj = {
        "FirstName":"John",
        "LastName":"Doe",
        "ID":1234,
        "QCR3m":null,
        "FR3m":null,
        "ERI3m":null,
        "QCR6m":null,
        "FR6m":null,
        "ERI6m":null,
        "QCR1y":90.05,
        "FR1y":null,
        "ERI1y":93.55,
        "QCR3y":93.51,
        "FR3y":95.86,
        "ERI3y":94.0,
        "QCR5y":93.25,
        "FR5y":95.86,
        "ERI5y":94.0
    };

console.log(Object.keys(obj).length);
like image 128
AmmarCSE Avatar answered Dec 15 '25 20:12

AmmarCSE