Search code examples
javascriptlaravelvue.jsaxiosvuex

How to show/manipulate specify values of objects array from backend in Vue?


For example, what if I need to sum a certain number (in this case, these are ids) that came from the database?

Laravel/api:

[ 
    { "id": 3, "created_at": null, "updated_at": null, "name": "Name One" }, 
    { "id": 4, "created_at": null, "updated_at": null, "name": "Name Two" } 
]

Component:

<template>
<div class="font-semibold text-4xl text-gray-600">
    {{showTotal}}
</div>

import {mapGetters, mapActions} from 'vuex';

export default {
    name: "Total",

    mounted() {
        this.fetchNames();
    },
    methods: {
        ...mapActions(["fetchNames"])
    },
    computed: {
        ...mapGetters(["getNames"]),
        showTotal() {
            return this.getNames[0]['id'] + this.getNames[1]['id']
        }
    },
}

I got errors in the console, but in Vue.js devtools there is showTotal: 7 Vue.js devtools Console errors

store/modules/names.js:

export default {
    state: {
        names: [],
    },
    getters: {
        getNames: state => state.names,
    },
    actions: {
        async fetchNames({commit}) {
            const response = await axios.get('/api/names');
            commit('setNames', response.data);
        },
    },
    mutations: {
        setNames: (state, names) => state.names = names,
    }
}

Solution

  • You would need reduce to iterate over array

    const names = [ 
        { "id": 3, "created_at": null, "updated_at": null, "name": "Name One" }, 
        { "id": 4, "created_at": null, "updated_at": null, "name": "Name Two" } 
    ]
    
    const total = names.reduce((total, current) => {
      return total += current.id;
    }, 0)
    
    console.log(total);

    So it would be

    showTotal() {
      return this.getNames.reduce((total, current) => {
        return total += current.id;
      }, 0)
    }