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

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

Posted by: admin November 26, 2021 Leave a comment

Questions:

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,
    }
}
Answers:

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)
}

###

The console error might be appearing due to this.getNames returning empty array the first time the component is rendered and the api hasn’t returned the response yet which is why when you try to access the 0 index’s id property it throws an error. (Maybe add in some checks to avoid this error)

You could also try a much simpler way of adding ids by using forEach. Code sample below:

showTotal() {
  let total = 0;
  this.getNames.forEach((item) => total += item.id);

  return total;
}