Getting the size of an array in an object

JavascriptArraysObjectCount

Javascript Problem Overview


I would like some help with getting the size of an array inside an object:

var st = { "itema":{...},"itemb":[{"id":"s01","cd":"c01","dd":"d01",....}{"id":"s02","cd":"c02","dd":"d02",....}]}

How would you get a count of the objects inside "itemb" (in this case 2)?

Javascript Solutions


Solution 1 - Javascript

Javascript arrays have a length property. Use it like this:

st.itemb.length

Solution 2 - Javascript

Arrays have a property .length that returns the number of elements.

var st =
    {
        "itema":{},
        "itemb":
        [
            {"id":"s01","cd":"c01","dd":"d01"},
            {"id":"s02","cd":"c02","dd":"d02"}
        ]
    };

st.itemb.length // 2

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmeliView Question on Stackoverflow
Solution 1 - JavascriptAndrew HareView Answer on Stackoverflow
Solution 2 - JavascriptBrunoLMView Answer on Stackoverflow