6

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.

Steve
  • 8,066
  • 11
  • 70
  • 112

1 Answers1

1

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

bluehipy
  • 2,254
  • 1
  • 13
  • 19
  • Is it possible to get the loop over the keys and values that we want to replace instead of the entire object? – Ryan Aug 10 '20 at 18:15