0

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,

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use flat Array function. Here:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.