Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

68
Views
Javascript reduce and map on nested array of objects

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,

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

You can use flat Array function. Here:

const data2 = data
  .map(state => state.payment.map(statePayment => [state.country, statePayment.paymentType, statePayment.count]))
  .flat();
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!