I want to output the number of all questions for each post in ReactJs. For this i created the next code:
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)
})
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.