morphism icon indicating copy to clipboard operation
morphism copied to clipboard

Help needed to flatten nest array within a object

Open imranmomin opened this issue 5 years ago • 0 comments

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

imranmomin avatar Sep 02 '20 18:09 imranmomin