'How to remove a object from a array of object based on a condition?
I have array of objects like this:
data = [
{
"name":"abc",
"email":"[email protected]"
},
{
"name": "bcd",
"email": "[email protected]",
"info":[
{
"email": "[email protected]",
"count":5
}
]
},
{
"name": "hfv",
"email": "[email protected]",
"info":[
{
"email": "[email protected]",
"count":5
},
{
"email": "[email protected]",
"count":7
}
]
}
]
I want to to change data in such a way that only objects that have count>1 should exist
so the output should like this:
[{
"name": "bcd",
"email": "[email protected]",
"info":[
{
"email": "[email protected]",
"count":5
}
]
},
{
"name": "hfv",
"email": "[email protected]",
"info":[
{
"email": "[email protected]",
"count":5
},
{
"email": "[email protected]",
"count":7
}
]
}
]
the data array should look like this, how I can I loop through this array of objects and remove objects that have count<=1?
Solution 1:[1]
You can use array.filter() to achieve it
const result = data.filter(obj => obj.info && obj.info.filter(info => info.count > 1).length > 0)
You may need to filter info objects as well... depends of your need. But you have everything you need here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LéoValette |
