The problem with your current approach is that you're not utilizing .filter
correctly. The .filter
method expects the function provided to return a boolean
. If true
is returned, the element will be kept in the new array. If it's false
, the element gets excluded. Therefore, rather than attempting to remove an element from test_arr
using .splice
, employ .filter
to determine what stays and what goes.
Additionally, note that in your case, v
pertains to a specific element (an object) within your test_array
. It implies that there's no need to target index 0
of the object; instead, retrieve the current object's id
.
var test_arr = [{"name":"qqq", "city":"it","id":"123456"}, {"name":"ggg", "city":"uk","id":"777456"}];
test_arr = test_arr.filter(function(elem) {
return elem.id !== '123456';
});
console.log(test_arr); // [{"name": "ggg", "city": "uk", "id": "777456"}]
If you prefer a more concise solution, you can utilize an arrow function combined with destructuring assignment:
test_arr = test_arr.filter(({id}) => id !== '123456'); // [{"name": "ggg", "city": "uk", "id": "777456"}]
var test_arr = [{"name":"qqq", "city":"it","id":"123456"}, {"name":"ggg", "city":"uk","id":"777456"}];
test_arr = test_arr.filter(({id}) => id !== '123456'); // [{"name": "ggg", "city": "uk", "id": "777456"}]
console.log(test_arr);