I am having some trouble to filter nested array data set. For example I have list of data array below:
let list = [
{
"percentage": 50.0,
"budget": "online",
"ruleName": "C1"
},
{
"percentage": 50.0,
"budget": "offline",
"ruleName": "C1"
},
{
"percentage": 50.0,
"budget": "other",
"ruleName": "C4"
}
]
Now I want to achieve following result using .map or .filter and considering the condition if the budget property of parent array and child group array matches then it should return only matched object inside group instead all:
[
{
"budget": "online",
"ruleName": "C1",
"group": [
{
"budget": "onlne",
"percentage": 50.0
}
]
},
{
"budget": "offline",
"ruleName": "C1",
"group": [
{
"budget": "offline",
"percentage": 50.0
}
]
},
{
"budget": "other",
"ruleName": "C4",
"group": [
{
"budget": "other",
"percentage": 0
}
]
}
]
So I performed below action but my result didn't match to my expected result above:
this.group = list.map((i)=>{
return {
budget: i.budget,
}
})
this.payments = list.map((i)=>{
return {
budget: i.budget,
amtPercentage: i.percentage ? i.percentage : 0,
rulename: i.rulename,
group: this.group
}
})
Here is following result after above code execution:
[
{
"budget": "online",
"ruleName": "C1",
"group": [
{
"budget": "onlne",
"percentage": 50.0
},
{
"budget": "offline",
"percentage": 50.0
},
{
"budget": "other",
"percentage": 0
}
]
},
{
"budget": "offline",
"ruleName": "C1",
"group": [
{
"budget": "onlne",
"percentage": 50.0
},
{
"budget": "offline",
"percentage": 50.0
},
{
"budget": "other",
"percentage": 0
}
]
},
{
"budget": "other",
"ruleName": "C4",
"group": [
{
"budget": "onlne",
"percentage": 50.0
},
{
"budget": "offline",
"percentage": 50.0
},
{
"budget": "other",
"percentage": 0
}
]
}
]
I don't have any clue how to filter the nested group array based on the condition where if parent array budget property equals to group.budget property then it should return only that object but not all.
I'll be very grateful for your help. Many thanks in advance.
Note: I am using typescript with angular-2.
this.payments = list.map((i)=>{
return {
budget: i.budget,
amtPercentage: i.percentage ? i.percentage : 0,
rulename: i.rulename,
group: this.group.filter((x) => i.budget === x.budget)
}
})
EDIT simplification:
this.payments = list.map((listElement) => ({
...listElement,
amtPercentage: listElement.percentage || 0,
group: this.group.filter((groupElement) => listElement.budget === groupElement.budget)
}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With