Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of elements in this json object? [duplicate]

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?

like image 968
guagay_wk Avatar asked Jul 27 '14 01:07

guagay_wk


People also ask

How do I count the number of elements in JSON?

USE len() TO COUNT THE ITEMS IN A JSON OBJECT. Call len(obj) to return the number of items in a JSON object obj.

How do you find the number of elements in a JSON array?

JsonArray::size() gets the number of elements in the array pointed by the JsonArray . If the JsonArray is null, this function returns 0 . Internally, this function walks a linked-list to count the elements, so its time complexity is O(n). Don't use this function to create a for loop; instead, use iterators.


1 Answers

You can use Object.keys:

 Object.keys(data).length; // returns 1
 Object.keys(data.name_data).length; // returns 4
like image 127
Khalid Avatar answered Oct 12 '22 11:10

Khalid