Ways to display/control specific values of objects array from backend in Vue

Imagine you have to calculate the total sum of specific numbers (in this case, IDs) retrieved from a 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']
        }
    },
}

In the console, there were errors reported. However, Vue.js devtools showed the correct total value as 7. Here are the screenshots for reference: Vue.js devtools and 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,
    }
}

Answer №1

You can utilize the reduce method to loop through an array

const items = [ 
    { "id": 3, "created_at": null, "updated_at": null, "name": "Item One" }, 
    { "id": 4, "created_at": null, "updated_at": null, "name": "Item Two" } 
]

const sum = items.reduce((total, current) => {
  return total += current.id;
}, 0)

console.log(sum);

In this case, you would do the following:

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

Answer №2

The console error pops up because this.getNames may initially return an empty array when the component is first rendered, and the API response has not been received yet. As a result, attempting to access the id property at index 0 triggers an error. To prevent this issue, consider adding some checks.

An alternative approach is to simplify the process of adding ids by utilizing forEach. Check out the code snippet below:

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

  return total;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Regular expression that allows alphanumeric characters and spaces, but does not permit spaces at the beginning or end of the

I need to create a regular expression that allows for a combination of letters, numbers, and spaces within a word, ranging in length from 3 to 50 characters, but without spaces at the beginning or end of the string. Here is the regex pattern I have come up ...

What is the process for incorporating a country, state, and city dropdown menu into Laravel forms?

Greetings! I am a beginner in using the Laravel framework. I have a form with three fields - country, state, and city - all to be displayed as select options. Can anyone provide guidance on how to implement these fields within the Laravel framework? Appre ...

Display and conceal HTML content using the value of AngularJS

I am looking to toggle the visibility of a <button> element on my HTML page based on the value of a directive {{auth?.loggedIn}} from AngularJS, whether it is true or false. This is how my HTML currently looks: <button (click)="onLogin()&quo ...

What is the most effective way to include JavaScript code in a PDF file?

What is the process for integrating JavaScript code into a PDF document? I am familiar with coding in JavaScript and would like to learn how to add it to a file in order to perform tasks such as displaying the current date or using a combobox. ...

What is the best way to position a Button at the bottom of a div using jQuery?

Within my HTML, I have divided into two col-md-6 sections. On the left side, there is a picture and on the right side, there is text. I am considering using jQuery .height() for this layout. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7 ...

What is the best way to determine the currently active component in Angular 5?

I am currently working on creating a settings button that will dynamically change its content based on the component that the user is viewing. I am unsure of the best practice for accomplishing this task. My initial thought is to utilize an Angular directi ...

Avoiding repetitive rendering of child components in ReactJS

In my React project, I have a parent component that contains 3 children components, structured like this: var Parent = React.createClass({ render: function() { return (<div> <C1/> <C2/> <C3/> ...

Can you provide guidance on implementing structured data jsonLD in a Next.js 13 application's router?

I have been struggling to implement structured data in my Next.js 13 (app router) application and have not been able to find the correct method. The next-seo package is also throwing errors for me. When I tried using next-seo, I encountered this error: ...

Ways to confirm non-null values and bypass the row if it is

I have been attempting to compare 2 dates in order to appropriately display data in a table. I have tried the following approach: ${this.dateToCompare.getTime()} > ${row.CreateDate.getTime()} However, there is an issue where CreateDate has a null value ...

Issue: Unspecified error when trying to access object attribute in Vue (Nuxt)

I am facing an issue with my 'region' object. It appears to be displayed correctly with all its attributes, but when I try to access specific attributes, it shows up as 'undefined'. const region = { "id": 7, "name": ...

AngularJS Enhanced Multi-Level Table

Currently, I'm attempting to display 3 tables on a single page that pull data from the same array but filter it using ng-repeat. I followed a similar table format from another source and you can view my JS Fiddle Link here: http://jsfiddle.net/6Texj/1 ...

Determine in jQuery whether a Value is present within a JSON dataset

[ { "link" : "images/examples/image-3.png", "image" : "images/examples/image-3.png", "title" : "copy" }, { "link" : "images/examples/image-3.png", "video" : "video placeholder", "title" : "c ...

How to efficiently group all keys in lodash using groupBy

I'm currently exploring ways to efficiently aggregate all items within a collection. Specifically, I am interested in identifying the most effective method using Lodash to group this set of objects by each of their keys (in depth), assuming that the ...

Setting up Type ORM configuration with a .env file in Nest.JS: A step-by-step guide

I encountered an issue while attempting to configure TypeORM with a .env file and run migration script. Here's what I tried: 1. Added scripts to package.json "migration:generate": "node_modules/.bin/typeorm migration:generate -n", "migratio ...

Having trouble with the Bootstrap card-header not functioning properly?

With Laravel 5.5, I've been exploring Bootstrap's 4 documentation and discovered that the card components are perfect for what I have in mind. However, I encountered an issue when attempting to create a simple card model: <div class="containe ...

Reduce the length of the text to 50 characters after the current word, while ensuring that the word

Looking for a way to shorten text after reaching 50 characters, making sure not to split words in the middle when cutting off. For example: Contrary to popular belief, Lorem Ipsum is not simply text (59 chars) Desired output: Contrary to popular belief, ...

Unable to perform a setter operation within a loop structure

I've been working on crafting a hero quest-style script lately. The script involves navigating through an array of events where the player either moves or encounters enemies, triggering a battle. After meticulously writing the script and reviewing i ...

Issue with JavaScript cookie not being recognized in server-side code

When I try to access Response.Cookies["alertsCookie"], it returns an empty cookie. To solve this issue, I decided to create two cookies as a workaround. I couldn't figure out how to read a cookie in a specific path, so I stored them in both the page ...

Adjust the template within a directive to dynamically include an additional directive

Challenge Create a custom directive that dynamically adds the ng-bind attribute, allowing for the use of ng-bind, ng-bind-html, or ng-bind-html-unsafe without needing to manually add it to the template definition throughout. Illustrative Example http://j ...

Passing Data Between Page and Component (NEXT.JS + LEAFLET Integration)

I have recently started using Next.js with Leaflet maps and have encountered a beginner's question. I created a page in Next.js ( /pages/map/[id].jsx ) that utilizes a component ( /component/Map.jsx ). Within the page ( [id].jsx ), I fetch a JSON fil ...