0

Using Nuxt async data, I am fetching a JSON object with a nested array in the following format:

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

The data is being loaded asynchronously:

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 would like to know what would be the best approach to calculating the sum total of all views. I am aware of reduce() and imagine these values need to be pushed into an array - but how to do this with data loaded asynchronously?

2
  • you need computed property for total, where you need to check for topics updates Commented Nov 13, 2018 at 12:48
  • How can you get all the views array data? res.data.views ? Commented Nov 13, 2018 at 12:55

1 Answer 1

1

Just sum 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 will add the views:

res.data.topic_list.topics.reduce((sum, currentItem) => (currentItem.views + sum), 0)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.