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

163
Views
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 answers
Answer question

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 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!