我从Web服务获取数据并根据收到的数据填充两个数组
price_table array = {
"10": [{
"_id": "59429018ff054c0001289199",
"price": {
"original": {
"value": 10,
"currency": "EUR",
"_id": "59429018ff054c00012891a4"
},
"selling": {
"value": 10,
"currency": "EUR",
"_id": "59429018ff054c00012891a3"
},
"allowProposals": false,
"_id": "59429018ff054c00012891a2"
},
"eventId": "b6901f78-28bf-11e7-8534-985aebe2005e",
"status": "ACTIVE",
"__v": 0
}],
"35": [{
"_id": "594290216f1127741550ea22",
"price": {
"original": {
"value": 12,
"currency": "EUR",
"_id": "594290216f1127741550ea2d"
},
"selling": {
"value": 35,
"currency": "EUR",
"_id": "594290216f1127741550ea2c"
},
"allowProposals": false,
"_id": "594290216f1127741550ea2b"
},
"eventId": "b6901f78-28bf-11e7-8534-985aebe2005e",
"status": "ACTIVE",
"__v": 0
},
{
"_id": "5942b36144d9f2cc788545e2",
"price": {
"original": {
"value": 34,
"currency": "EUR",
"_id": "5942b36144d9f2cc788545ed"
},
"selling": {
"value": 35,
"currency": "EUR",
"_id": "5942b36144d9f2cc788545ec"
},
"allowProposals": false,
"_id": "5942b36144d9f2cc788545eb"
},
"eventId": "b6901f78-28bf-11e7-8534-985aebe2005e",
"status": "ACTIVE",
"__v": 0
}
]
}
for (let price in price_table) {
if (price_table.hasOwnProperty(price)) {
ticketPrice.push(price.toString());
ticketPriceData.push(price_table[price].length);
}
}
这将生成两个数组,如下所示,
ticketPrice = ['10','13'];
ticketPriceData = [1,2];
现在我生成的ticketPrice数组缺少值,其中mintocal为10,maxtocal为13
while (mintocal < maxtocal) {
if (ticketPrice.indexOf(mintocal.toString()) === -1) {
ticketPrice.push(mintocal.toString());
ticketPriceData.push(0);
}
mintocal++;
}
这会生成数组
ticketPrice数组为
["10","13","11","12"]
和ticketPriceData为
[1,2,0,0]
我真正想要的是
输出预期:
ticketPrice
:[“10”,“11”,“12”,“13”]
ticketPriceData
:[1,0,0,2]
答案 0 :(得分:0)
您要做的是创建一个新数组,因为您拥有的数组已经填充了值。你需要做的是:
var ticketPrice = [];
var ticketPriceData = [];
while (mintocal < maxtocal) {
var index = ticketPrice.indexOf(mintocal.toString());
newTicketPrice.push(mintocal.toString());
newTicketPriceData.push((index === -1) ? 0 : ticketPriceData[index]);
mintocal++;
}
我们在这里做的是推送ticketPriceData值(如果它存在于原始数组中,如果不存在则为0。
在您的解决方案中,数组['10','13']
被推送&#39; 11&#39;结果为['10', '13', '11']
,然后推送'12'
,结果为['10','13','11', '12']
如果您希望解决方案在不创建新阵列的情况下工作,则可以在看到它时从两个阵列中删除该值并在最后重新插入它。这将是这样做的:
while (mintocal < maxtocal) {
var i = ticketPrice.indexOf(mintocal.toString());
if (i === -1) {
ticketPrice.push(mintocal.toString());
ticketPriceData.push(0);
} else {
var value = ticketPrice.splice(i,1);
var data = ticketPriceData.splice(i,1);
ticketPrice.push(value);
ticketPrice.push(data);
}
mintocal++;
}