String splicing from array by value

I want to combine a string 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 splicing or just a loop of this code works.

But, both show this error:

Uncaught TypeError: Cannot read property '0' from undefined (...)

This happens in "data.rows [i] [0]"

+5
source share
4 answers

You can iterate with Array # forEach () :

 var data = {"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]]}, del = 3; // Value of ID to be deleted data.rows.forEach(function(item, index) { item[0] === del && data.rows.splice(index, 1); }); console.log(data.rows); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

ES6

 data.rows.forEach((item, index) => item[0] === del && data.rows.splice(index, 1)); 
+1
source

instead of using a for loop, id uses an array filter function:

 data.rows = data.rows.filter(function(row){ return row[0] !== del; }); 
+3
source

Just add a break condition to the condition because the next element is the one you spliced โ€‹โ€‹that is no longer in the array.

 if (del == id) { // if del = id -> splice data.rows.splice(i, 1); break; // no more to search } 
+2
source

You can use lodash to filter your objects or arrays. Look at the filtering method for your case:

 var myObject = { "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]] }; //filter by lodash myObject.rows = _.filter(myObject.rows,function(row){ return row[0] !== 3; }); 
0
source

Source: https://habr.com/ru/post/1259828/


All Articles