Home > front end >  How to sum array value with v-for Vue 3 Composition API
How to sum array value with v-for Vue 3 Composition API

Time:11-24

I have table and array like screenshot below: enter image description here

I want to sum the value, for example in tfoot row "Jumlah": 4, 4, 4

My table script:

                    <table >
                        <thead>
                            <tr>
                                <th scope="col">Kecamatan</th>
                                <th scope="col">Desa</th>
                                <th scope="col" v-for="(form, index) in formFields" :key="index">
                                    {{ form.title }}
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(item, index) in datas" :key="index">
                                <td>{{ item.kecamatan !== null ? item.kecamatan.name : '-' }}</td>
                                <td>{{ item.desa !== null ? item.desa.name : '-' }}</td>
                                <td v-for="(field, index) in JSON.parse(item.fieldDatas)" :key="index">
                                    {{ field.value }}
                                </td>
                                <td v-if="forms.length >= JSON.parse(item.fieldDatas).length"
                                    v-for="(n, i) in (forms.length - JSON.parse(item.fieldDatas).length)">0</td>
                            </tr>
                        </tbody>
                        <tfoot>
                            <tr v-for="(item, index) in datas" :key="index">
                                <td colspan="2">Jumlah</td>
                                <td v-for="(field, index) in JSON.parse(item.fieldDatas)" :key="index">
                                    {{ field }}
                                </td>
                            </tr>
                        </tfoot>
                    </table>

CodePudding user response:

I think you can calculate the footData using computed like this.

const footData = computed(
  () =>
    data.reduce((acc, item) => {
      JSON.parse(item.fieldDatas).forEach((field) => {
        if (!field.id) return;
        acc = {
          ...acc,
          [field.id]: (acc?.[field.id] ?? 0)   (field?.value ?? 0),
        };
      });
      return acc;
    }, {}),
);
  • Related