I have an array of objects called data
and also have a separate object that is called mapping
.
I try to delete the invalid object from the array. I have iterated the array using the map
function
. I check whether the object is valid using the mapping
object. If it is found to be invalid then it should be deleted from the array, but the map function is not working asynchronously so they skip the invalid object, which is pushed into the array which is not fine. so please suggest some solution and also give me the small detail why map function is skipping the object.
Here my code:
const data = [
{
id: 11,
name: "dashboard",
},
{
id: 13,
name: "card",
},
{
id: 1,
name: "user",
},
{
id: 4,
name: "test",
},
];
const mapping = {
1: "dashboard",
2: "user",
3: "card",
4: "test",
};
const filterData = () => {
data.map((parent, i) => {
if (Object.keys(mapping).includes(parent.id.toString())) {
} else {
const index = data.indexOf(parent);
if (index > -1) {
data.splice(index, 1);
}
}
});
console.log("updated data", data);
};
```
wrong output
[
{ id: 13, name: "card" },
{ id: 1, name: "user" },
{ id: 4, name: "test" }
];