how to group array of objects by value in reactjs / javascript

社会主义新天地 提交于 2020-04-10 05:27:13

问题


I have an array of object that have different values like

 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 "}]

I use array map to list the object and display them as

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

My question is how do i iterate the item so as it groups the items by category as follows

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

cat_2
- My title 2
- Another title 2

cat_3
-Third Title

回答1:


Use .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);



回答2:


I would make CertainPerformance's answer a bit more concise:

    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);



回答3:


I use lodash in a lot of projects as a general utility belt. If you decide to do something similar -- it would be simple as:

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/lodash@4.17.5/lodash.min.js"></script>


来源:https://stackoverflow.com/questions/49462145/how-to-group-array-of-objects-by-value-in-reactjs-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!