Y
Y
yellow_pus2022-04-11 00:06:35
Laravel
yellow_pus, 2022-04-11 00:06:35

How to properly reduce posts to categories, through a relationship?

I have a controller that returns data like this in api:

,{"id":6,"category_name":"333","posts":[{"title":"111","description":"222"}]},{"id":7,"category_name":"333","posts":[{"title":"123123","description":"32131"}]}

That is, two different arrays, for the same category 333, are a post with a title 111and a post with a title 123123. How, or maybe even a condition, can I put these two articles in the same category.
Or still do it somehow at the front? I have vuejs there, in which I display this data in such a cycle
<div v-for="post in posts.data">
        Категория: {{ post.category_name }} <br>
        Посты:
        <div v-for="p in post.posts">
            {{ p.title }}
        </div>
        <br>
        -----------------------
    </div>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2022-04-11
@0xD34F Vue.js

computed: {
  categories() {
    return this.posts.data.reduce((acc, n) => (
      (acc[n.category_name] ??= {
        name: n.category_name,
        posts: [],
      }).posts.push(...n.posts),
      acc
    ), {});
  },
  ...

<div v-for="category in categories">
  <h3>{{ category.name }}</h3>
  <div v-for="post in category.posts">
    {{ post.title }}
  </div>
</div>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question