Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jscodeshift change object literal value

Using jscodeshift, how can I transform

// Some code ...

const someObj = {
  x: {
    foo: 3
  }
};

// Some more code ...

to

// Some code ...

const someObj = {
  x: {
    foo: 4,
    bar: '5'
  }
};

// Some more code ...

?

I have tried

module.exports = function(file, api, options) {
    const j = api.jscodeshift;
    const root = j(file.source);

    return root
        .find(j.Identifier)
        .filter(path => (
            path.node.name === 'someObj'
        ))
        .replaceWith(JSON.stringify({foo: 4, bar: '5'}))
        .toSource();
}

but I just end up with

// Some code ...

const someObj = {
  {"foo": 4, "bar": "5"}: {
    foo: 3
  }
};

// Some more code ...

which suggests that replaceWith just changes the key instead of the value.

like image 505
Steve Avatar asked Nov 07 '22 23:11

Steve


1 Answers

You have to search for the ObjectExpression rather than for the Identifier:

module.exports = function(file, api, options) {
  const j = api.jscodeshift;
  const root = j(file.source);

  j(root.find(j.ObjectExpression).at(0).get())
    .replaceWith(JSON.stringify({
      foo: 4,
      bar: '5'
    }));

  return root.toSource();
}

Demo

like image 170
bluehipy Avatar answered Nov 15 '22 06:11

bluehipy