Suming value of child table in parent table

Suming value of child table in parent table

carrarachristophecarrarachristophe Posts: 129Questions: 31Answers: 2

Hello,
I refer to the parent child editor.
Is there a way to, instead of counting the number of users

        {
            data: 'users',
            render: (data) => data.length
        }

We make the sum of a users' field, for example their age?

I found this post but I am not sure it is pointing me in the right direction.

Thanks and regards

Answers

  • kthorngrenkthorngren Posts: 22,503Questions: 26Answers: 5,171

    You should be able to make any calculations you want. Looking at the developer tools for the JSON response in the example you linked to this shows an example of one row of data in the parent:

            {
                "DT_RowId": "row_1",
                "id": "1",
                "name": "Edinburgh",
                "users": [
                    {
                        "id": "1"
                    },
                    {
                        "id": "7"
                    },
                    {
                        "id": "13"
                    },
                    {
                        "id": "19"
                    },
                    {
                        "id": "25"
                    },
                    {
                        "id": "31"
                    }
                ]
            },
    

    The columns.render function is just presenting the length of the users array. The columns.render function will need changed depending on your data structure. Please provide an example of a row of data so we can help with suggestions.

    Kevin

  • carrarachristophecarrarachristophe Posts: 129Questions: 31Answers: 2

    I tried the follwing (dummy example)

    {
        data: 'users',
        render: (data) => data.reduce((sum, user) => sum + (user.phone || 0), 0)
    }
    

    without success

  • allanallan Posts: 65,972Questions: 1Answers: 10,980 Site admin

    In the example you mentioned, the only value in the users array is an id (per the JSON that Kevin shows in his post above). There isn't a .phone parameter to access under the objects in that array. You could sum the .id parameter, although that isn't exactly useful! You'd need to make sure that the returned JSON includes whatever value it is that you wish to sum.

    Allan

Sign In or Register to comment.