简体   繁体   中英

Remove array from json array wrt if condition in React JSX

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},
]

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.

You should create a new one of Array, You can try..

let temp = []
response.forEach((res, index) => {
    if (res.status !== 1) {
        temp.push(res)
    }
})

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM