Home > Software design >  Javascript reduce and map on nested array of objects
Javascript reduce and map on nested array of objects

Time:04-01

i have an array of objects in

[
  {
    "country": "USA",
    "payment": [
      {
        "paymentType": "Visa",
        "count": 1000
      },
      {
        "paymentType": "MasterCard",
        "count": 1000
      }
    ]
  },
  {
    "country": "CANADA",
    "payment": [
      {
        "paymentType": "Visa",
        "count": 1000
      },
      {
        "paymentType": "MasterCard",
        "count": 1000
      }
    ]
  },
  {...}
]

I want to transform it into

[
["USA" , "VISA" , 10000 ], 
["USA","Mastercard",1000],
[countryName2, paymentType,count] , ...
]

Can someone help me>?

I tried doing :

const data2 = data.map(function(elem) {
  return [
    elem.country,
    elem.payment.map(b=> b.paymentType),
    elem.payment.map(c=>c.count),
  ]
})

but the output i get is not what i want, if someone could show how to do it,

CodePudding user response:

You can do this with a nested map where each array entry is created by extracting data from payment prefixed with the outer country.

const data = [{"country":"USA","payment":[{"paymentType":"Visa","count":1000},{"paymentType":"MasterCard","count":1000}]},{"country":"CANADA","payment":[{"paymentType":"Visa","count":1000},{"paymentType":"MasterCard","count":1000}]}];

const data2 = data.flatMap(({ country, payment }) =>
  payment.map(({ paymentType, count }) => [
    country,
    paymentType,
    count
  ])
);

console.log(data2);
.as-console-wrapper { max-height: 100% !important; }

The flatMap() on the outer map removes the extra level of nesting created in the result.

CodePudding user response:

You can use flat Array function. Here:

const data2 = data
  .map(state => state.payment.map(statePayment => [state.country, statePayment.paymentType, statePayment.count]))
  .flat();
  • Related