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?
USE len() TO COUNT THE ITEMS IN A JSON OBJECT. Call len(obj) to return the number of items in a JSON object obj.
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.
You can use Object.keys
:
Object.keys(data).length; // returns 1
Object.keys(data.name_data).length; // returns 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With