我一直在努力解决这个问题,但是我一点也没有运气。我尝试了各种方法,其中一种是forEach
数组方法,但无法获得所需的输出。
我有以下数组:
[
{ "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
{ "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
{ "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
{ "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
{ "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 },
{ "CAT": "SANDWICHES", "QTY": 1, "PRICE": 7.5 }
]
我需要将其分成相等的部分,如下所示:
[
{ "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
{ "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
{ "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]
[
{ "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
{ "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
{ "CAT": "SANDWICHES", "QTY": 1, "PRICE": 7.5 }
]
抱歉,如果解释不太好。
想法是,每个块都必须具有以下值的所有3个元素。1x冷饮1x三明治1个QUICK BITES
餐费:$ 2.99-1x三明治,1x饮料和1x速食小吃的组合。
第二个数组仅在所有3个值都存在时才应创建。如果仅存在两个值,则循环应中断。
我尝试过的:
var ITM ="";
var PER_CATEGORY_SET = [];
var value = [
{ "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
{ "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
{ "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
{ "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
{ "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 },
{ "CAT": "SANDWICHES", "QTY": 1, "PRICE": 7.5 }
]
value.forEach(function (my_item){
var xx = value.length;
while (xx > 0) {
if(ITM != my_item.CAT ){
ITM = my_item.CAT;PER_CATEGORY_SET.push({'CAT':my_item.CAT,'QTY':my_item.QTY,'PRICE':my_item.PRICE});
value.splice(0, 1);
}
xx--;
}
});
我得到的输出如下,它只能创建初始数组,而不执行任何操作:
[
{ "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
{ "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
{ "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]
希望对您有帮助
let arr = [
{"CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2},
{"CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5},
{"CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5},
{"CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5},
{"CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3},
{"CAT": "SANDWICHES", "QTY": 1, "PRICE": 7.5}
]
let arr1 = [], arr2 = []
for (let i = 0; i < arr.length; i++ ){
if(i%2==0) {
arr1.push(arr[i])
} else {
arr2.push(arr[i])
}
}
console.log(arr1,arr2)
创建2个新数组并循环遍历原始数组一次。如果我是偶数,则推入第一个数组,否则推入第二个数组。
const originalArray = [
{"CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2},
{"CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5},
{"CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5},
{"CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5},
{"CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3},
{"CAT": "SANDWICHES", "QTY": 1, "PRICE": 7.5}
]
var firstChunk = [];
var secondChunk = [];
for(var i = 0; i<originalArray.length; i++){
if(i%2 === 0){
firstChunk.push(originalArray[i]);
}
else{
secondChunk.push(originalArray[i]);
}
}
您可以分别通过firstChunk和secondChunk访问这两个卡盘