A
A
Andrew2018-12-01 15:36:41
Vue.js
Andrew, 2018-12-01 15:36:41

How to create an array with objects from another array?

Vue has an array with objects:

posts: [
    {
      title: 'Тестовый пост',
      content: 'lorem lorem',
      category: 'lifestyle'
    },
    {
      title: 'Тестовый пост',
      content: 'lorem lorem',
      category: 'lifestyle'
    },
    {
      title: 'Тестовый пост',
      content: 'lorem lorem',
      category: 'business'
    },
    {
      title: 'Тестовый пост',
      content: 'lorem lorem',
      category: 'travel'
    },
    {
      title: 'Тестовый пост',
      content: 'lorem lorem',
      category: 'travel'
    },
  ]
}
Нужно создать отдельный массив с постами каждой отдельной категории (travel, lifestyle, business). Как это лучше сделать?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-12-01
@AndrewRusinas

computed: {
  groupedPosts() {
    return this.posts.reduce((acc, n) => {
      (acc[n.category] = acc[n.category] || []).push(n);
      return acc;
    }, {});
  },
},

UPD. What the author of the question actually wanted is taken from the comments:
You make two computed properties - an array of categories, and an array of posts of the selected category, something like this .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question