javascriptabstract-syntax-treejscodeshift

Create a codemod to add a new element to array


I have been struggling to adding a new object to array of objects with jscodeshift. My problem is I can't figure out how I have to query an array after I got VariableDeclarator. I need to get a last element in the array after that I can insert a new node. Here is the code:

export default function transformer(file, api) {

    const j = api.jscodeshift;
    const root = j(file.source);
    const changeList = root.find(j.VariableDeclarator, {
        id: {name: 'list'},
    }).closest(j.ArrayExpression, {
        elements: [""]
    }).replaceWith(p => {
        console.log(p);
    }).toSource();

};

I am playing with it on AST explorer


Solution

  • .closest returns the closest ancestor node matching the type. The ArrayExpression is a descendant though, so you have to use .find again. This works:

    export default function transformer(file, api) {
    
      // import jscodeshift
        const j = api.jscodeshift;
        // get source code 
    
        const root = j(file.source);
        // find a node
    
        return root.find(j.VariableDeclarator, {id: {name: 'list'}})
        .find(j.ArrayExpression)
        .forEach(p => p.get('elements').push(j.template.expression`x`))
        .toSource();
    };