How to remove an item from array of objects:
[
{
"category": "CC",
"paymentOptions": [
{
"payCode": "v",
"description": "Visa"
},
{
"payCode": "m",
"description": "Master"
}
]
},
{
"category": "PayPal",
"paymentOptions": [
{
"payCode": "PY",
"description": "Paypal"
}
]
}]
I want to remove this section from the above array of objects:
{
"payCode": "m",
"description": "Master"
}
After removing the above section my array should be like:
[
{
"category": "CC",
"paymentOptions": [
{
"payCode": "v",
"description": "Visa"
}
]
},
{
"category": "PayPal",
"paymentOptions": [
{
"payCode": "PY",
"description": "Paypal"
}
]
}]
I have tried the below code but does not return the desired result:
this.payments.filter(x => x.paymentOptions.filter(x => x.description.toLowerCase() !="Master"))
How to do that and I need an output as above after removing the specific object
>Solution :
You are trying to remove the item with description: "master" in paymentOptions array for each element in the payments array.
-
With
x.description.toLowerCase() !="Master", this will be never betrue. -
Use the
Array.map()to iterate and update thepaymentOptionsarray for each element.
let result = this.payments.map(x => ({
...x,
paymentOptions: x.paymentOptions.filter(y => y.description.toLowerCase() != "master")
}));