jscodeshift convert forEach to for loop

268 Views Asked by At

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.

1

There are 1 best solutions below

1
Will Brock On

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
    )
});