Skip to content

Help needed to flatten nest array within a object #201

@imranmomin

Description

@imranmomin

Hi,

I'm trying to use the library to map the below source to a flat version

Source

{
  "id": "2",
  "type": "plan",
  "name": "silver",
  "pricings": [
    {
      "amount": {
        "currency": "cad",
        "value": 5.99
      },
      "interval": {
        "type": 1,
        "duration": 30
      }
    },
    {
      "amount": {
        "currency": "cad",
        "value": 9.99
      },
      "interval": {
        "type": 2,
        "duration": 90
      }
    }
  ]
}

Target

{
       "id": "2",
       "name": "silver",
       "amount": {
           "currency": "cad",
           "value": 5.99
       },
       "interval": {
           "type": 1,
           "duration": 30
       }
   },
   {
       "id": "2",
       "name": "silver",
       "amount": {
           "currency": "cad",
           "value": 9.99
       },
       "interval": {
           "type": 2,
           "duration": 90
       }
   }

To achieve the above i'm using flatMap function. I tried couple of ways using StrictSchema

const result = plans.flatMap(x => {
    const plan = {
        id: x.id,
        name: x.name
    }

    return x.pricings.map(p => <Plan>{
        ...plan,
        amount: p.amount,
        interval: p.interval
    });
});

Also, many times I need to do reverse mapping i.e. from Target to Source and for that I use reduce function

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions