I have a json array:
[
{"id":19,"name":"Jed", "lastname":"DIAZ", "hobby":"photo", "birthday":"2011/11/22"},
{"id":20,"name":"Judith", "lastname":"HENDERSON", "hobby":"pets", "birthday":"1974/06/12"},
{"id":21,"name":"Nicolai", "lastname":"GRAHAM", "hobby":"reading", "birthday":"2005/01/22"},
{"id":22,"name":"Vasile", "lastname":"BRYANT", "hobby":"singing", "birthday":"1987/03/17"}
]
function to remove a item from json array
removeItem: function(removeId){
//paramater validation
return dataLoad.then(function(data){
f = data.findIndex(function(item) { return item.id == removeId; });
if(f < 0)
return false;
data.splice(f,1);
LS.setData(data,"cutomers");
return true;
});
}
When the code is running there is an error:
findIndex is not a function
error line
f = data.findIndex(function(item) { return item.id == removeId; });
findIndex
is not a prototype method of Array
in ECMASCRIPT 262, you might need filter
combined with indexOf
, instead, it has the advantage of stopping searching as soon as entry is found
var f;
var filteredElements = data.filter(function(item, index) { f = index; return item.id == removeId; });
if (!filteredElements.length) {
return false;
}
data.splice(f, 1);
EDIT as suggested in comments by Nina Scholz:
This solution is using Array.prototype.some
instead
var f;
var found = data.some(function(item, index) { f = index; return item.id == removeId; });
if (!found) {
return false;
}
data.splice(f, 1);
Found at Array.prototype.findIndex MDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With