【发布时间】:2021-10-11 12:54:58
【问题描述】:
我正在开发一个模仿零售网站的 React 应用程序。我的主页显示一个项目,下面有相关产品的卡片组件。当我单击其中一个相关产品上的按钮时,我会打开一个比较模式,用于比较当前产品和点击产品的功能。我认为要实现这一点,我将创建一个包含点击产品和主页产品的组合功能的数组。我一直在努力创建一个对象数组,其中每个独特的功能都有一个对象,其中包含有关功能的数据以及该功能所属的产品。
截至目前,我已经能够获得两个产品具有的所有功能的数组,但是如果产品具有重叠的功能,则该数组会重复。这让我不确定如何呈现比较表,因为我计划映射数组并为每个特征创建一个表行。我当前格式化这些功能的代码如下:
formatFeatures: (currentProd, clickedProd) => {
let combinedFeatures = [];
if (clickedProd.features) {
clickedProd.features.forEach(feature => {
let obj = {}
let vals = Object.values(feature);
obj[vals[0]] = [vals[1], clickedProd.id]
combinedFeatures.push(obj)
})
}
currentProd.features.forEach(feature => {
let obj = {}
let vals = Object.values(feature);
obj[vals[0]] = [vals[1], currentProd.id]
combinedFeatures.push(obj)
})
let formattedFeatures = combinedFeatures.reduce((allFeatures, feature) => {
if (Object.keys(feature) in allFeatures) {
allFeatures = [allFeatures[Object.keys(feature)]].concat(feature);
} else {
allFeatures.push(feature);
}
return allFeatures;
}, [])
这样的结果是:
[{
"Fabric": ["100% Cotton", 28214]
}, {
"Cut": ["Skinny", 28214]
}, {
"Fabric": ["Canvas", 28212]
}, {
"Buttons": ["Brass", 28212]
}]
这与我正在寻找的非常接近,其中我有一组对象,其中包含有关产品的功能和产品 ID 的信息,但是“Fabric”中的重复是我正在努力解决的问题.理想情况下,结果如下所示:
[{
"Fabric": ["100% Cotton", 28214],
["Canvas", 28212]
}, {
"Cut": ["Skinny", 28214]
}, {
"Buttons": ["Brass", 28212]
}]
如果有人可以帮助指导我如何更改我的格式化功能以完成此操作,我将不胜感激。或者,如果有人知道一种更好的方法,可以根据我当前的结果,为每个独特功能动态设置单行格式的表格,那也很棒。
进入我的辅助函数的数据如下:
当前产品:
{
"id": 28212,
"name": "Camo Onesie",
"slogan": "Blend in to your crowd",
"description": "The So Fatigues will wake you up and fit you in. This high energy camo will have you blending in to even the wildest surroundings.",
"category": "Jackets",
"default_price": "140.00",
"created_at": "2021-07-10T17:00:03.509Z",
"updated_at": "2021-07-10T17:00:03.509Z",
"features": [{
"feature": "Fabric",
"value": "Canvas"
}, {
"feature": "Buttons",
"value": "Brass"
}]
}
点击产品:
{
"name": "Morning Joggers",
"category": "Pants",
"originalPrice": "40.00",
"salePrice": null,
"photo": "https://images.unsplash.com/photo-1552902865-b72c031ac5ea?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=300&q=80",
"id": 28214,
"features": [{
"feature": "Fabric",
"value": "100% Cotton"
}, {
"feature": "Cut",
"value": "Skinny"
}]
}
【问题讨论】:
-
没有,谢谢大家
标签: javascript arrays reactjs dictionary reduce