jscodeshift change object literal value
Asked Answered
H

1

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.

Heller answered 11/4, 2017 at 8:21 Comment(0)
B
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

Blackbird answered 4/9, 2017 at 7:51 Comment(2)
Is it possible to get the loop over the keys and values that we want to replace instead of the entire object?Magnuson
Is it possible to read plain JSON or does the JSON have to be assigned to a const?Arboretum

© 2022 - 2024 — McMap. All rights reserved.