Using Vue/Nuxt.js to compute the cumulative sum of hierarchically structured JSON data

When using Nuxt async data, I am retrieving a JSON object that includes a nested array in the following structure:

"topic_list": {
    "topics": [
      {
        "id": 9148,
        "title": "A",
        "views": 12
      },
      {
        "id": 3228,
        "title": "B",
        "views": 88
      }
      ]
}

The data is loaded asynchronously as shown below:

export default {
  data () {
    return { topics: 'default', users: '0', views: '0', total: [] }
  },
  asyncData ({ params }, callback) {
    axios.get(`data.json`)
    .then((res) => {
      callback(null, { topics: res.data.topic_list.topics, users: res.data.users,

      })
    })
  }
}

I am looking for guidance on how to calculate the total number of views efficiently. I know I can use reduce() and assume the values need to be placed into an array, but how would this be done with asynchronously loaded data?

Answer №1

Simply sum up all the views

      callback(null, { topics: res.data.topic_list.topics, users: res.data.users, totalOfViews: 
res.data.topic_list.topics.reduce((sum, currentItem) => (currentItem.views + sum), 0) })

This calculation will aggregate the views:

res.data.topic_list.topics.reduce((sum, currentItem) => (currentItem.views + sum), 0)

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

Unable to modify a record using the 'findById' method and save() function while utilizing promises

I am in the process of developing a cinema application using Node.js and MongoDB with Mongoose. One specific requirement I have is to update the 'Show' model when a user places an order. The task involves adding the latest seats that were ordere ...

Is there a way to convert a Java object into a JSON string while ensuring that all special characters are

Is there a method to transform a Java object into a string with the following criteria? It is important that all field names are properly escaped, and the records are separated by "\n". { "content":"{\"field1\":123, \"field2\":1, ...

Enabling Bootstrap modal windows to seamlessly populate with AJAX content

I'm currently in the process of crafting a bootstrap modal that displays the outcome of an AJAX request. Below is my bootstrap code: {{--Bootstrap modal--}} <div id="exampleModal" class="modal" tabindex="-1" role="dialog"> <div class="m ...

What is the best way to send data from ajax to a django view?

I have a script for ajax that retrieves the public key and sends other details to the Stripe server for payment. However, I am struggling with sending the dynamic value of the price to item_line. fetch("/config/") .then((result) => { return re ...

What is the solution to the error message "A TypeError was encountered in the current module: e.parse is not a function"?

Can someone please help me resolve this Vue Js error I am encountering in Shopware 6 Administration? The issue pertains to selecting a column in the database table using a module. Note: Below is the complete code snippet. I am attempting to retrieve data ...

Only perform the Rails ajax call once initially

I'm currently working on creating a drop down menu that contains a substantial amount of content, and I would like to use an ajax get call to load everything upon mouse enter. Here is my code written in coffeescript: class @SecondaryMenu construct ...

What is the process for including a field specific to a date in a form?

I need the user to select a month and year. In one column, there will be the days of the month they selected [e.g. 1-30]. Users can then add habits in other columns. I want users to be able to input an 'X' for each habit row on a specific date [e ...

Unable to Interpret JSON in Universal Windows Platform

I developed a UWP application that parses data to JSON format. The JSON data can be found here. However, I am facing issues with parsing the "jawaban" section of the JSON data which is causing an error message to appear like this: https://i.stack.imgur.co ...

Exploring the firestore section with vuefire for seamless access to methods

I am attempting to access a method in the firestore section of vuefire, but encountering the following error: vue-router.esm.js?8c4f:2257 TypeError: Cannot read property 'messagesWith' of undefined at eval (Chat.vue?62f3:214) This is the lin ...

What is the best way to position a div to float or hover from the bottom after it has been

I am working on creating a menu where clicking it will reveal a submenu at the bottom, but I'm encountering an issue. Currently, in my code, the submenu is appearing from right to left before moving down. Here is my code: <meta name="viewport" co ...

Show only the image source (img src) and do not display the audio and video sources using jQuery

In my code, I need the following conditions to be met: when an image is posted from the backend, the video and audio sources should automatically hide; when a video is posted, the image and audio sources should hide; and when an audio file is posted, the v ...

Jackson will not convert null values using a personalized Serializer

One issue I encountered was with a custom bean serializer in Jackson that resulted in null properties being excluded from the output JSON. To reproduce the problem, consider the following code snippet: // Code example goes here Upon running the above cod ...

Detecting repeated keys in a query for a REST connector in loopback

Can anyone help me figure out how to duplicate parameters in a loopback REST connector query? Here's the code snippet I'm working with: details: { 'template': { 'method': 'GET', 'debug': tr ...

When attempting to pass Rgraph image data through a jQuery AJAX call, a 403 Forbidden error is being

I have been working on a project that involves creating graphs/charts using the Rgraph PHP library. To generate these charts, my script follows these steps: Calculate the graph points and render the graph using the Rgraph Draw() method. Create an image d ...

Wrap it in a ReactJS container tag

Today I encountered a frustrating issue while diving into ReactJS. I'm excited to learn by getting my hands dirty, but unfortunately, I keep running into this error: Adjacent JSX elements must be wrapped in an enclosing tag (47:14) And here's t ...

Tips on implementing a Javascript function triggered by a user's click within the video player frame

<script> function greet() { alert("hello"); } </script> <iframe width="100%" height="315" src="https://www.youtube.com/embed/AGM0ibP1MRc" onclick="greet()"></iframe> .Kindly assist me, please. ...

I keep encountering an attach() error every time I try to close a modal that contains a vee-validated form

Every time I try to close a bootstrap modal (using bootstrap-vue) that includes a vee-validated "update" form with vue.js, I encounter the following error: main.js:477686 Uncaught (in promise) Error: [vee-validate] Validating a non-existent field: "#35". ...

Tips for choosing specific elements of an array for pagination in php

If I have arrays structured like this: [0] => Array{ [name]=>ABC } [1] => Array{ [name]=>ABC } [2] => Array{ [name]=>ABC } [3] => Array{ [name]=>ABC } [4] => Array{ [name]=>ABC } [5] => Array{ [name]=>ABC } ...

How can I efficiently extract data from JSON by incorporating variables?

Currently, I am utilizing C# to parse JSON data. The following code functions perfectly: var json = webClient.DownloadString("API KEY"); Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(json); Consol ...

The jQuery Show Hide feature is experiencing issues specifically on Internet Explorer

Everything looks good in Firefox and Chrome, but unfortunately it's malfunctioning in IE. Does anyone have a suggestion for hiding select Dropdown options? I attempted using CSS with display: none but it didn't work. $j("#id option[value=&apos ...