10

I want to get the number of elements for this JSON object in javascript.

data = 
{
    name_data: {
        35: {
            name: "AA",
        },
        47: {
            name: "BB",
        },
        48: {
            name: "CC",
        },
        49: {
            name: "DD",
        }
    }
}

The correct answer should be 4. My code is data.name_data.length but it returns an undefined object. How can the correct number of elements in this JSON object be obtained in javascript?

guagay_wk
  • 26,337
  • 54
  • 186
  • 295

1 Answers1

31

You can use Object.keys:

 Object.keys(data).length; // returns 1
 Object.keys(data.name_data).length; // returns 4
Khalid
  • 4,730
  • 5
  • 27
  • 50