如何在reactjs / javascript中按值对对象数组进行分组

问题描述 投票:2回答:3

我有一个具有不同值的对象数组

 items=[{id:1,category:"cat_1" , title:"My title 1"},{id:2,category:"cat_2" , title:"My title 2"},{id:6,category:"cat_1" , title:"Another title 1"},{id:1,category:"cat_3" , title:"My title 3"},{id:8,category:"cat_1" , title:"Third Title"},{id:2,category:"cat_2" , title:"Another title 2 "}]

我使用数组映射列出对象并将其显示为

     {
     items.map((item) => (
        <h1>{item.category}</h1>
        <p>{item.title}</p>
    ))} 

我的问题是如何迭代项目,以便按类别对项目进行分组,如下所示

cat_1
- My title 1
- Another title 1
- My title 3

cat_2
- My title 2
- Another title 2

cat_3
-Third Title
javascript reactjs loops foreach group-by
3个回答
8
投票

使用.reduce

const items = [{
  id: 1,
  category: "cat_1",
  title: "My title 1"
}, {
  id: 2,
  category: "cat_2",
  title: "My title 2"
}, {
  id: 6,
  category: "cat_1",
  title: "Another title 1"
}, {
  id: 1,
  category: "cat_3",
  title: "My title 3"
}, {
  id: 8,
  category: "cat_1",
  title: "Third Title"
}, {
  id: 2,
  category: "cat_2",
  title: "Another title 2 "
}];
const cats = items.reduce((catsSoFar, { category, title }) => {
  if (!catsSoFar[category]) catsSoFar[category] = [];
  catsSoFar[category].push(title);
  return catsSoFar;
}, {});
console.log(cats);

1
投票

我会使CertainPerformance的答案更简洁:

    const items = [{
      id: 1,
      category: "cat_1",
      title: "My title 1"
    }, {
      id: 2,
      category: "cat_2",
      title: "My title 2"
    }, {
      id: 6,
      category: "cat_1",
      title: "Another title 1"
    }, {
      id: 1,
      category: "cat_3",
      title: "My title 3"
    }, {
      id: 8,
      category: "cat_1",
      title: "Third Title"
    }, {
      id: 2,
      category: "cat_2",
      title: "Another title 2 "
    }];
    const cats = items.reduce((catMemo, { category, title }) => {
      (catMemo[category] = catMemo[category] || []).push(title);
      return catMemo;
    }, {});
    console.log(cats);

0
投票

我在许多项目中使用lodash作为通用实用带。如果你决定做类似的事情 - 它会很简单:

const data = [{
  id: 1,
  category: "cat_1",
  title: "My title 1"
}, {
  id: 2,
  category: "cat_2",
  title: "My title 2"
}, {
  id: 6,
  category: "cat_1",
  title: "Another title 1"
}, {
  id: 1,
  category: "cat_3",
  title: "My title 3"
}, {
  id: 8,
  category: "cat_1",
  title: "Third Title"
}, {
  id: 2,
  category: "cat_2",
  title: "Another title 2 "
}];

const groups = _.groupBy(data,  'category');

console.log(groups);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.