Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 753
rob111 Avatar asked Oct 26 '25 14:10

rob111


1 Answers

.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();
};
like image 70
Felix Kling Avatar answered Oct 29 '25 14:10

Felix Kling