javascript - 我的arrayPizzas有问题,如果它永远不会进入第一个,问题是什么?我想为重复的列表项添加计数 ++
问题描述
this.arrayPizzas = [
0: {
name: "4 Stagioni",
price: 13,
ingredients: "250 g of pizza dough, 150 g of tomato sauce, 30 g …ck and green olives, 30 g of champignon mushrooms",
image: "../assets/img/pizza-4stag.png"
},
1: {
name: "Margherita",
price: 10,
ingredients: "Manitoba flour 200 g, Water 300 ml, Salt up to 10 g, Extra virgin olive oil 35 g, Tomato pulp 500 g",
image: "../assets/img/pizza-margherita.png"
},
2: {
name: "Margherita",
price: 10,
ingredients: "Manitoba flour 200 g, Water 300 ml, Salt up to 10 g, Extra virgin olive oil 35 g, Tomato pulp 500 g",
image: "../assets/img/pizza-margherita.png"
},
3: {
name: "Margherita",
price: 10,
ingredients: "Manitoba flour 200 g, Water 300 ml, Salt up to 10 g, Extra virgin olive oil 35 g, Tomato pulp 500 g",
image: "../assets/img/pizza-margherita.png"
},
4: {
name: "Vegetarian",
price: 13.5,
ingredients: "400 g of pizza dough, 300 g of tomato sauce, 1 eggplant, 2 peppers, 1 courgette",
image: "../assets/img/pizza-vegetariana.png"
},
5: {
name: "Vegetarian",
price: 13.5,
ingredients: "400 g of pizza dough, 300 g of}];
this.arrayPizzas = this.local.sort((a, b) => (a.name > b.name) ? 1 : -1);
this.arrayPizzas.forEach(element => {
const count = 0;
if (this.newArray.includes(element.name)) {
console.log('include');
this.newArray[element].counter = element.counter + 1;
} else if (!this.newArray.includes(element.name)) {
console.log('else');
const a: Cart = {
name: element.name,
counter: count,
price: element.price
};
this.newArray.push(a);
}
});
解决方案
这将为您工作并计算披萨名称的出现次数
arrayPizzas = [{
name: "Margherita",
price: 10,
ingredients: "Manitoba flour 200 g, Water 300 ml, Salt up to 10 g, Extra virgin olive oil 35 g, Tomato pulp 500 g",
image: "../assets/img/pizza-margherita.png"
},
{
name: "Vegetarian",
price: 13.5,
ingredients: "400 g of pizza dough, 300 g of tomato sauce, 1 eggplant, 2 peppers, 1 courgette",
image: "../assets/img/pizza-vegetariana.png"
},
{
name: "Vegetarian",
price: 13.5,
ingredients: "400 g of pizza dough, 300 g of"
}
]
newArray = [];
this.arrayPizzas.forEach((element) => {
const index = this.newArray.findIndex(x => x.name === element.name)
if (index > -1) {
this.newArray[index].counter += 1
} else {
const a = {
name: element.name,
counter: 1,
price: element.price
};
this.newArray.push(a);
}
});
console.log(newArray)
推荐阅读
- python - 附加到列表时值重复
- java - 来自 CSV 的 BeanIO 读取字段,代表一个集合
- python - Discord py自动反应问题
- javascript - 在浏览器模式下使用 Mocha.js 获取不会处理或抛出错误
- webpack - 为什么在编译我的 SASS 模块时出现“模块解析失败”?
- python - 在数组周围填充零以强制它具有相同的长度
- python - 如何按特定 ID 合并多行而不丢失其他列?
- java - Aeron:Archive taggedReplicate 是否应该与 C 媒体驱动程序一起使用?
- pandas - 根据条件替换一行中的值
- php - WooCommerce 购物篮图标显示为正方形