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

时间:2014-03-18 17:11:50

标签: javascript jquery json for-loop

所以,这个购物车,就像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.

所以,我希望防止在那里有两次相同的值,并按照id匹配它们。

这是我目前的解决方案(作为蟑螂的小车,并没有真正完成这项工作),因为它唯一有效的时间是匹配值是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的值idtuoteID相同,则应运行addToExisting()。如果JSON的值与tuoteID不同,请运行addNew()

但是怎么样?

1 个答案:

答案 0 :(得分:1)

您可以使用some检查ID是否已存在。 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();
}

Fiddle