如何在reactjs / javascript中按值对对象数组进行分组
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在reactjs / javascript中按值对对象数组进行分组相关的知识,希望对你有一定的参考价值。
我有一个具有不同值的对象数组
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
答案
使用.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);
另一答案
我会使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);
另一答案
我在许多项目中使用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/lodash@4.17.5/lodash.min.js"></script>
以上是关于如何在reactjs / javascript中按值对对象数组进行分组的主要内容,如果未能解决你的问题,请参考以下文章
在React JS中按下输入时如何实现onChange事件[重复]