8

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?

user781486
  • 20,909
  • 45
  • 145
  • 253

1 Answers1

28

You can use Object.keys:

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