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

164
Vistas
jscodeshift convert forEach to for loop

I'm new to jscodeshift and AST but I'm trying to do a conversion for my existing forEach loops and convert them to regular for loops.

I want to covert the below:

[
    `foo`,
    `bar`
].forEach(test => {
    console.log(test);
});

To this:

for(const test of  [`foo`, `bar`]) {
  console.log(test);
}
export default (file, api) => {
  const j = api.jscodeshift;
  const root = j(file.source);

  // What do I do here to transform the forEach to a regular for loop?

  return root.toSource();
};

I've been looking through some of the docs and searching but I can't find a way to do this.

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

The is what I was looking for.

root.find(j.CallExpression, {
    callee : {
        property : {
            name : "forEach"
        }
    }
})
.replaceWith(path => {
    // Hangles foo.forEach() and [1,2].forEach()
    const expression = path.value.callee.object.name ? j.identifier(path.value.callee.object.name) : j.arrayExpression(path.value.callee.object.elements);

    return j.forOfStatement(
      j.variableDeclaration(
            "const",
            path.value.arguments[0].params
      ),
      expression,
      path.value.arguments[0].body
    )
});
about 4 years ago · Santiago Gelvez 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