问题描述
我使用 Redux 将我的所有产品存储在一个列表中。显示的这个列表看起来像:
[
{
"id": 1,"name": "BLACK TEA","supplieruuid": "SLIGRO",},{
"id": 2,"name": "GREEN TEA",{
"id": 3,"name": "PURPLE TEA","supplieruuid": "BUNZL",{
"id": 4,"name": "RAINBOW TEA",]
我正在使用这个 reduce 函数通过键 supplieruuid 将这些产品组合在一起。
export const selectSortedItems = (state) => state.entities.cart.list.reduce((hash,{ ["supplieruuid"]: value,...rest }) => ({ ...hash,[value]: (hash[value] || []).concat({ ...rest }) }),{});
这将返回按关键供应商 uuid 分组的产品数组。
[
{
"SLIGRO": [
{
"id": 1,{
"id": 2,],"BUNZL": [
{
"id": 3,{
"id": 4,]
除了我需要返回如下:
[
{
title: "SLIGRO",data: [
{
"id": 1,{
title: "BUNZL",data: [
{
"id": 3,]
解决方法
保持您的 selectSortedItems
原样,我们可以创建另一个函数来根据您的需要映射它。
const selectSortedItems = (state) => {
const sortedBySupplierUUID = state.entities.cart.list.reduce((hash,{ ["supplieruuid"]: value,...rest }) => ({ ...hash,[value]: (hash[value] || []).concat({ ...rest }) }),{});
return Object.keys(selectSortedItems(sortedBySupplierUUID)).map(key => ({ title: key,data: sortedBySupplierUUID[key] }))};
}
,
当您使用 reduce 时,您需要传递一个空的 []
作为累加器。
其次,您需要搜索该元素是否存在于 acc
数组中。如果它存在,那么您将对象推送到 acc 中,否则添加一个具有 2 个属性 title
和 data
的新对象。
const arr = [
{
id: 1,name: "BLACK TEA",supplieruuid: "SLIGRO",},{
id: 2,name: "GREEN TEA",{
id: 3,name: "PURPLE TEA",supplieruuid: "BUNZL",{
id: 4,name: "RAINBOW TEA",];
const result = arr.reduce((acc,curr) => {
const { supplieruuid } = curr;
const objInAcc = acc.find((o) => o.title === supplieruuid);
if (objInAcc) objInAcc.data.push(curr);
else acc.push({ title: supplieruuid,data: [curr] });
return acc;
},[]);
console.log(result);
您可以对一个对象进行分组,并使用不需要的数据属性进行解构。最后只取对象的值。
const
data = [{ id: 1,supplieruuid: "SLIGRO" },{ id: 2,{ id: 3,supplieruuid: "BUNZL" },{ id: 4,supplieruuid: "BUNZL" }],result = Object.values(data.reduce((r,{ supplieruuid: title,...o }) => {
(r[title] ??= { title,data: [] }).data.push(o);
return r;
},{}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }