You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 06:39:13