I want splice the line with value = 3
[3,"John", 90909090]
data.json
{
"headers":[[
{"text":"Code","class":"Code"},
{"text":"Code","class":"Code"}
]],
"rows":[
[0,"Peter", 51123123],
[3,"John", 90909090],
[5,"Mary",51123123]
],
"config":[[0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],
"other":[[13,0]]
}
I try this:
var size = data.rows.length; // number of rows
var del = 3 // Value of ID to be deleted
for (i = 0; i < size; i++) {
var id = data.rows[i][0];
if(del==id){ // if del = id -> splice
data.rows.splice(i,1);
}
}
Results:
Only splice or only loop this code works.
But, with both show this error:
Uncaught TypeError: Cannot read property '0' of undefined(…)
It occurs in "data.rows[i][0]"
Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.
The splice() method is used to add or remove elements of an existing array and the return value will be the removed items from the array. If nothing was removed from the array, then the return value will just be an empty array. Here is the basic syntax. In this example, we have an array of food items.
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
It's not working because you are removing items from the array while looping through the keys. When you remove an item, it will rearrange the other items depending on how the array is implemented internally, and you end up with a loop that doesn't iterate over the keys that you expect.
instead of using a for loop, id use the array filter function:
data.rows = data.rows.filter(function(row){
return row[0] !== del;
});
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