通过匹配ID检查json数组中是否已经存在item

Check if item already exists in json array by matching ID

本文关键字:是否 item 存在 数组 json ID 检查      更新时间:2023-09-26

这是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"}}]

格式化。

所以,我想防止在那里有两次相同的值,并通过它们的id s进行匹配。

这是我目前的解决方案(像蟑螂一样有bug,并没有真正完成这项工作),因为它唯一有效的时候是匹配值在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()

但如何?

您可以使用some检查id是否已经存在。some的美妙之处在于:

如果找到这样的元素,some立即返回true。

如果你是迎合旧的浏览器,在该页的底部有一个填充。

function hasId(data, id) {
  return data.some(function (el) {
    return el.tuote.id === id;
  });
}
hasId(data, '4'); // true
hasId(data, '14'); // false

:

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

小提琴