Alf17
Alf17

Reputation: 3

how to count array data inside array in react.js?

I'm trying to count total of comment from these comments, but it only count 2 data, I am using res.data.length, and I don't know how to count only 5 data which is only comment inside comments, I mean it should count 5 data but it only count 2 data

here json

{
        "comments": [
            {
                "comment": "comment 1.1"
            },
            {
                "comment": "comment 1.2"
            }
        ],
        "date": "2019-10-22T20:21:04.927Z",
        "_id": "5daf65c8bcaab30224def48f",
        "caption": "caption 1",
        "picture": "https://ichef.bbci.co.uk/news/976/media/images/83351000/jpg/_83351965_explorer273lincolnshirewoldssouthpicturebynicholassilkstone.jpg",
        "__v": 0
    },
    {
        "comments": [
            {
                "comment": "comment 2.1"
            },
            {
                "comment": "comment 2.1"
            }
            {
                "comment": "comment 2.1"
            },
        ],
        "date": "2019-10-23T05:30:16.210Z",
        "_id": "5dafe7876688d3064073eed0",
        "caption": "ini caption 2",
        "picture": "https://helpx.adobe.com/content/dam/help/en/stock/how-to/visual-reverse-image-search/jcr_content/main-pars/image/visual-reverse-image-search-v2_intro.jpg",
        "__v": 0
    }

here the code

componentDidMount() {
        const url = "http://localhost:5000/api/comments/";
        axios.get(url).then(res => {
          this.setState({
              isLoaded: true,
              comments: res.data,
              countComment: res.data.length
          })
        })      

    }

Upvotes: 0

Views: 1688

Answers (1)

Nicolas Hevia
Nicolas Hevia

Reputation: 15837

Expanding my comment with a solution. Go to the second example to view a solution for the code you just edited

// simulate axios response
const res = {} 
res.data = [
  {
    comments: [
      {
        comment: 'comment 1.1'
      },
      {
        comment: 'comment 1.2'
      }
    ],
    caption: 'caption 1'
  },
  {
    comments: [
      {
        comment: 'comment 2.1'
      },
      {
        comment: 'comment 2.2'
      },
      {
        comment: 'comment 2.3'
      }
    ],
    caption: 'caption 2'
  }
]

let commentCount = 0
// iterate through each item, you need this
res.data.forEach(data => {
  commentCount += data.comments.length
})
console.log(commentCount) // 5

Usage in your scenario:

componentDidMount() {
  const url = "http://localhost:5000/api/comments/";
  axios.get(url).then(res => {
    let commentCount = 0 
    res.data.forEach(data => {
      commentCount += data.comments.length
    })
    this.setState({
        isLoaded: true,
        comments: res.data,
        countComment: commentCount
    })
  })      
}

You can check these MDN articles:
JavaScript object basics and Arrays

Upvotes: 2

Related Questions