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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With