如何使用JSCodeShift将对象属性包裹到另一个属性中
JSCodeShift:将对象属性包裹到新属性中
问题描述
我是JSCodeShift新手,正在用它进行现有代码转换,大部分功能已实现,但卡在将文件中对象的所有属性包裹到另一个新属性的步骤。网上找不到合适的示例代码,能获取对象属性但不知如何转换,尝试多种方法均未成功。
输入代码
const apiConfig = { url, location, method: 'GET', params: { test: 'test' }, spinnerConfig: { ... } }
期望输出代码
const apiConfig = { apiRequestOptions: { url, location, method: 'GET', params: { test: 'test' }, spinnerConfig: { ... }, }, }
初始尝试的JSCodeShift代码
export const parser = 'tsx' export default function transformer(file, api) { const j = api.jscodeshift; const root = j(file.source); return root .find(j.ObjectExpression) .filter(x => x.parentPath.parentPath.value.id.name == 'apiConfig') .forEach((path) => { // For each object literal path.value.properties.forEach((property) => { // go through each property if (property.type !== "ObjectProperty") return; // transform the obj here }) }).toSource(); }
已解决的更新代码
我已成功完成转换,更新后的代码如下:
export const parser = 'tsx' export default function transformer(file, api) { const j = api.jscodeshift; const root = j(file.source); return root .find(j.ObjectExpression) .filter(x => x.parentPath.parentPath.value.id.name == 'apiConfig') .forEach((path) => { const newObj = j.property( 'init', j.identifier('apiRequestOptions'), j.objectExpression([ ...path.value.properties // spread the properties ]) ); path.value.properties = [] // mutate original path.value.properties.push(newObj) // add a new one }) }).toSource(); }
内容的提问来源于stack exchange,提问作者j.doe
相关产品推荐
相关产品推荐

