【发布时间】:2014-03-18 17:11:50
【问题描述】:
所以我有这个购物车,作为 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"}}]
所以,我想防止其中两次出现相同的值,并通过它们的ids 匹配它们。
这是我目前的解决方案(像蟑螂一样的越野车,并没有真正完成这项工作),因为它唯一有效的时候是匹配值在 JSON 字符串中的第一个时。
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 是 json,如果您想知道的话。正如您可能看到的,对于 JSON 中包含的每个项目,addNew() 将运行的次数越多。
所以基本上,如果 JSON 具有与 tuoteID 相同的 id 值,则 addToExisting() 应该运行。如果 JSON 没有与 tuoteID 相同的值,请运行 addNew()。
但是怎么做呢?
【问题讨论】:
-
您可以维护一个正在添加的 id 数组,如果数组中没有 obj id,则用于下一个 obj 插入。
标签: javascript jquery json for-loop