Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

69
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda