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

212
Visualizações
Best practices with nested arrays in javascript

I'm currently working with nested arrays in an API response, and there is some info I need to extract.

In the example below, I want to extract the values from the "PaymentTypeName" obj key, and my code looks like that:

data.forEach(({ ModelList }) => {
  ModelList.forEach(({ CountryList }) => {
    CountryList.forEach(({ PaymentTypeList }) => {
      PaymentTypeList.forEach(({ PaymentTypeName }) => {
        console.log(PaymentTypeName);
      });
    });
  });
});

Where "data" is my API response.

I want to know: is there a better/cleaner code approach than this nested "forEach" calls? Is it considered a bad practice?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you can simplify the data structure, that will be the best approach.

If the structure is outside your control, the way you have written it is fine for a 'one-off' extraction of nested data. However, if you're constantly extracting nested data at different paths, writing forEach() will be laborious and you might want to consider a helper function to make it easier.

I wrote a helper that is executed like so:

const paymentTypes = getValuesAtPath(data, ['ModelList', 'CountryList', 'PaymentTypeList', 'PaymentTypeName']);

The function itself uses reduce() and is recursive.

 const data =[
  {
    "ModelList": [
      {
        "CountryList": [
          {
            "PaymentTypeList": [
              {
                "PaymentTypeName": "paypal"
              },
              {
                "PaymentTypeName": "check"
              }
            ]
          },
          {
            "PaymentTypeList": [
              {
                "PaymentTypeName": "credit card"
              }
            ]
          }
        ]
      },
      {
        "CountryList": [
          {
            "AnotherInterestingField": "look at me",
            "PaymentTypeList": [
              {
                "PaymentTypeName": "cash"
              }
            ]
          }
        ]
      }
    ]
  }
];

const getValuesAtPath = (data, path) => data.reduce((acc, item) => {
  const key = path[0];
  const value = item[key];
  if (value === undefined) return acc;

  // if at end of nested tree
  if (path.length === 1){
    return [...acc, value];
  }
  return [...acc, ...getValuesAtPath(value, path.slice(1, path.length))];
}, []);

const result = getValuesAtPath(data, ['ModelList', 'CountryList', 'PaymentTypeList', 'PaymentTypeName']);

console.log(result);

This helper can now be reused to extract other properties too:

getValuesAtPath(data, ['ModelList', 'CountryList', 'AnotherInterestingField'])
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