javascript - Check if item already exists in json array by matching ID -
so i've shopping cart, 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, want prevent having same value in there twice, , match them ids.
this current solution (buggy cockroach, doesn't job), time works when matching value first in json string.
for (var = 0; < ostoskori.length; i++) { if (ostoskori[i].tuote.id == tuoteid) { addtoexisting(tuoteid, tuotemaara); //this doesn't matter, works. break //the loop should stop if addtoexisting() runs } if (ostoskori[i].tuote.id != tuoteid) { addnew(tuoteid, tuotenimi, tuotemaara, tuotehinta); //this doesn't matter, works. //break //adding break here stop loop, //which prevents addtoexisting() function running } } ostoskori json if you're wondering. can see, each item json has inside it, more times addnew() run.
so basically, if json has value same id tuoteid, addtoexisting() should run. if json doesn't have value same tuoteid, run addnew().
but how?
you use some check if id exists. beauty of some is:
if such element found, returns true.
if you're catering older browsers there's polyfill @ bottom of 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(); }
Comments
Post a Comment