如何计算react.js中数组内部的数组数据?

时间:2019-10-31 02:37:27

标签: reactjs axios

我正在尝试计算这些评论中的评论总数,但它只计算2个数据,我使用的是res.data.length,我不知道如何仅计算5个数据,这些数据仅是评论内部的评论,我的意思是应该计算5个数据,但只能计算2个数据

这里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
    }

此处是代码

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

    }

1 个答案:

答案 0 :(得分:0)

用解决方案扩大我的评论。转到第二个示例以查看您刚刚编辑的代码的解决方案

// 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

您的方案中的用法:

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

您可以查看以下MDN文章:
JavaScript object basicsArrays