简体   繁体   中英

Check if item already exists in json array by matching ID

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 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM