Filter the elements according to another value

前端 未结 2 1784
慢半拍i
慢半拍i 2021-01-27 13:33

I want to output the number of all questions for each post in ReactJs. For this i created the next code:

相关标签:
2条回答
  • 2021-01-27 13:54

    const posts = [{
            title: 1,
            id: "123"
        },
        {
            title: 2,
            id: "1234"
        },
        {
            title: 3,
            id: "12345"
        }
    ]
    
    const questions = [{
            id: 55,
            name: 'question one',
            id_post: 123
        },
        {
            id: 56,
            name: 'question two',
            id_post: 123
        },
        {
            id: 57,
            name: 'question three',
            id_post: 1234
        },
        {
            id: 58,
            name: 'question four',
            id_post: 123
        },
    
    ];
    
    
    posts.map(({id}) => {
      let count = 0
      console.log(questions.filter(({id_post}) => (id_post == id)).length)
      
    })

    0 讨论(0)
  • 2021-01-27 14:04

    One possible approach is doing this count beforehand:

    const questionCountByPost = questions.reduce((acc, q) => {
      const postId = q.id_post;
      acc[postId] = (acc[postId] || 0) + 1;
      return acc;
    }, {});
    

    ... which looks like a nice thing to do each time either your posts or questions change. You can use this object inside your map function like this:

    return (
      <Link key={k} to={`demo/${e.id}/url`}>
      { questionCountByPost[e.id] }
      </Link>
    )
    

    Another approach is doing this count directly in template:

    return (
      <Link key={k} to={`demo/${e.id}/url`}>
      { questions.filter(q => q.id_post === e.id).length }
      </Link>
    )
    

    It's less performant (as you'll have to iterate through the whole array each time), but apparently more readable. If the number of posts and questions is not that big, it might a better solution.

    0 讨论(0)
提交回复
热议问题