【发布时间】:2021-10-21 12:22:51
【问题描述】:
我有一个对象数组如下。
const arr = [
{
categoryId: "I01",
categoryName: "Category_one",
price: 100
},
{
categoryId: "I02",
categoryName: "Category_two",
price: 200
},
{
categoryId: "I03",
categoryName: "Category_three",
price: 300
},
{
categoryId: "I02",
categoryName: "Category_two",
price: 210
},
{
categoryId: "I03",
categoryName: "Category_three",
price: 310
}
]
我正在努力获得如下结果。这就像根据类别过滤整个数组。
arr2 = [
{
id: 0,
categoryId: "I01",
categoryName: "Category_one",
minimum_price: 100,
count: 1
},
{
id: 1,
categoryId: "I02",
categoryName: "Category_two",
minimum_price: 200,
count: 2
},
{
id: 2,
categoryId: "I03",
categoryName: "Category_three",
minimum_price: 300,
count: 2
},
]
我已将结果创建到以下级别
const resArr = [];
arr.forEach((item) => {
let i = resArr.findIndex(x => x.categoryId == item.categoryId);
if (i <= -1) {
resArr.push({ categoryId: item.categoryId, categoryName: item.categoryName });
}
});
resArr.forEach((o, i) => o.id = i);
得到了这个结果,
res = [
{
id: 0,
categoryId: "I01",
categoryName: "Category_one"
},
{
id: 1,
categoryId: "I02",
categoryName: "Category_two"
},
{
id: 2,
categoryId: "I03",
categoryName: "Category_three"
},
]
我需要有 minimum_price 值和 count 值。非常感谢您的建议。
【问题讨论】:
标签: javascript arrays sorting reduce