So I've this shopping cart, as JSON.
[{tuote:{id:2,name:Rengas 2,count:16,price:120.00}},{tuote:{id:1,name:Rengas 6,count:4,price:25.00}},{tuote:{id:4,name:Rengas 4,count:4,price:85.00}}]
So, I want to prevent from having the same value in there twice, and match them by their id
s.
This is my current solution (buggy as a cockroach, doesn't really do the job), as the only time it works is when the matching value is first in the JSON string.
for (var i = 0; i < ostoskori.length; i++) {
if (ostoskori[i].tuote.id == tuoteID) {
addToExisting(tuoteID, tuoteMaara); //this doesn't matter, it works.
break //the loop should stop if addToExisting() runs
}
if (ostoskori[i].tuote.id != tuoteID) {
addNew(tuoteID, tuoteNimi, tuoteMaara, tuoteHinta); //this doesn't matter, it works.
//break
//adding break here will stop the loop,
//which prevents the addToExisting() function running
}
}
ostoskori
is the json if you're wondering. As you can probably see, for each item the JSON has inside it, the more times addNew()
will run.
So basically, if the JSON has a value with the same id
as tuoteID
, addToExisting()
should run. If the JSON doesn't have a value same as tuoteID
, run addNew()
.
But how?