Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
96
rated 0 times [  100] [ 4]  / answers: 1 / hits: 5513  / 10 Years ago, tue, march 18, 2014, 12:00:00

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}}]


Formatted here.



So, I want to prevent from having the same value in there twice, and match them by their ids.



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?


More From » jquery

 Answers
3

You could use some to check if the id already exists. The beauty of some is:




If such an element is found, some immediately returns true.




If you're catering for older browsers there's a polyfill at the bottom of that page.



function hasId(data, id) {
return data.some(function (el) {
return el.tuote.id === id;
});
}

hasId(data, '4'); // true
hasId(data, '14'); // false


So:



if (hasId(data, '4')) {
addToExisting();
} else {
addNew();
}


Fiddle


[#46750] Tuesday, March 18, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reed

Total Points: 725
Total Questions: 85
Total Answers: 89

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
;