Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda