I have a json array:
JavaScript
x
7
1
[
2
{"id":19,"name":"Jed", "lastname":"DIAZ", "hobby":"photo", "birthday":"2011/11/22"},
3
{"id":20,"name":"Judith", "lastname":"HENDERSON", "hobby":"pets", "birthday":"1974/06/12"},
4
{"id":21,"name":"Nicolai", "lastname":"GRAHAM", "hobby":"reading", "birthday":"2005/01/22"},
5
{"id":22,"name":"Vasile", "lastname":"BRYANT", "hobby":"singing", "birthday":"1987/03/17"}
6
]
7
function to remove a item from json array
JavaScript
1
16
16
1
removeItem: function(removeId){
2
//paramater validation
3
return dataLoad.then(function(data){
4
5
f = data.findIndex(function(item) { return item.id == removeId; });
6
7
if(f < 0)
8
return false;
9
data.splice(f,1);
10
11
LS.setData(data,"cutomers");
12
13
return true;
14
});
15
}
16
When the code is running there is an error:
findIndex is not a function
error line
JavaScript
1
2
1
f = data.findIndex(function(item) { return item.id == removeId; });
2
Advertisement
Answer
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
JavaScript
1
10
10
1
var f;
2
var filteredElements = data.filter(function(item, index) { f = index; return item.id == removeId; });
3
4
5
if (!filteredElements.length) {
6
return false;
7
}
8
9
data.splice(f, 1);
10
EDIT as suggested in comments by Nina Scholz:
This solution is using Array.prototype.some
instead
JavaScript
1
9
1
var f;
2
var found = data.some(function(item, index) { f = index; return item.id == removeId; });
3
4
if (!found) {
5
return false;
6
}
7
8
data.splice(f, 1);
9
Found at Array.prototype.findIndex MDN