这个问题在这里已经有了答案:
How can I group an array of objects by key?
(29 个回答)
9 个月前关闭。
社区在 9 个月前审查了是否重新打开此问题并将其关闭:
原始关闭原因未解决
我得到如下数据:
data.filter = {
selectedFilterItems: [
{
name: "0-435",
categoryId: "0_435",
code: "price",
totalItems: 1,
},
{
name: "MULTI",
categoryId: "7608",
count: 633,
code: "color",
subcategories: [],
totalItems: 1,
},
{
name: "Pastel Tie Dye",
categoryId: "566962",
count: 1,
code: "color",
subcategories: [],
totalItems: 1,
},
],
totalItems: 3,
};
我需要创建一个如下所示的 json,其中类型将是我从上述数据(即 data.filter)中获得的“代码”& 该值将以逗号分隔,用于通用代码。
所需输出 :
filters: [
{
type: 'price',
value: '0-435'
}
]
exg 颜色只有一种类型 = 颜色,其值为“MULTI,Pastel Tie Dye”。如果 data.filter 中只有一个不同的代码,那么只有该数据会在过滤器中。
这是我正在尝试的代码
if(data.filter) {
const selectedFilterItems = data.filter.selectedFilterItems.reduce((property, attribute) => {
if (property[attribute.code]) {
property[attribute.code].value += `,${attribute.name}`;
} else {
property[attribute.code] = { type: attribute.code, value: attribute.name };
}
return property;
}, {});
filter_data = Object.values(selectedFilterItems);
}
我需要添加到“filter_data”变量。{
type: 'category',
value: '7608' // where the value will be there "selectedFilterItems's any of the property's categoryId's value.
}
最佳答案
您可以使用 reduce()
过滤数据并使用 Object.values()
提取数据
const data = { selectedFilterItems: [ { name: "0-435", categoryId: "0_435", code: "price", totalItems: 1, }, { name: "MULTI", categoryId: "7608", count: 633, code: "color", subcategories: [], totalItems: 1, }, { name: "Pastel Tie Dye", categoryId: "566962", count: 1, code: "color", subcategories: [], totalItems: 1, }, ], totalItems: 3, };
const groupByData = data.selectedFilterItems.reduce((acc, b) => {
if (acc[b.code]) {
acc[b.code].value += `,${b.name}`;
} else {
acc[b.code] = { type: b.code, value: b.name };
}
return acc;
}, {});
const output = Object.values(groupByData);
console.log(output);
关于javascript - 基于对象创建数据集(javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68918802/