Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove specific nested object from array of arrays in TypeScript

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
{
    "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.

  1. With x.description.toLowerCase() !="Master", this will be never be true.

  2. Use the Array.map() to iterate and update the paymentOptions array for each element.

let result = this.payments.map(x => ({
  ...x,
  paymentOptions: x.paymentOptions.filter(y => y.description.toLowerCase() != "master")
}));

Demo @ TypeScript Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading