Search code examples
javascripttypescriptjavascript-objects

JavaScript dictionary data length


{
    "F1.1": {
        "add": [
            {
                "id": 169138,
                "name": "volkswagen"
            },
            {
                "id": 173212,
                "name": "skoda"
            }
        ],
        "delete": [
            {
                "id": 175555,
                "name": "mercedes"
            }
        ]
    }
}

I'm not been able to get length of add and delete array F1.1 is dynamic value, hence we cannot rely on it. How can we get the array lengths?


Solution

  • const data = {
        "F1.1": {
            "add": [
                {
                    "id": 169138,
                    "name": "volkswagen"
                },
                {
                    "id": 173212,
                    "name": "skoda"
                }
            ],
            "delete": [
                {
                    "id": 175555,
                    "name": "mercedes"
                }
            ]
        }
    };
    
    // Get the dynamic property names
    const dynamicProperties = Object.keys(data["F1.1"]);
    
    // Iterate through the dynamic properties and get the lengths
    dynamicProperties.forEach(property => {
        const arrayLength = data["F1.1"][property].length;
        console.log(`Length of ${property} array: ${arrayLength}`);
    });