Reputation: 45
How to remove an array from json array in react js. I tried something like this. but not working
Now the response is directly set to atate as follows
let { newData} = response;
please help to filter item. Either from response or from state variable
response.map((res, index) => {
if (res.status==1) {
res.splice(index, 1) // remove element
};
})
response is [object Object] when i alerted
[
{id:1, status:1},
{id:2, status:0},
{id:3, status:1},
]
Upvotes: 0
Views: 2128
Reputation: 930
The better solution is to use the filter method, or if you still want to use the splice, It should be response.splice
Note: Using the splice approach is wrong as pointed out by @VLAZ, as it shifts the elements but the indexing by forEach will continue irrespective of the elements spliced off.
var response = [
{id:1, status:1},
{id:2, status:0},
{id:3, status:1},
]
response.forEach((res, index) => {
if (res.status==1) {
response.splice(index, 1) // remove element
};
})
console.log(response);
Upvotes: 0
Reputation: 238
You should create a new one of Array, You can try..
let temp = []
response.forEach((res, index) => {
if (res.status !== 1) {
temp.push(res)
}
})
Upvotes: 1
Reputation: 1646
Use filter instead of map and filter out the unwanted object/s.
const filteredArray = response.filter((res) => res.status !== 1);
Please just be aware that this will create a new array and not mutate your original array.
Upvotes: 2