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

如何遍历嵌套对象数组,将所有type值替换为对应映射数值?

解决方案:递归遍历嵌套结构替换type值

你可以用递归函数处理这种嵌套的数组/对象结构,它能自动深入到每一层嵌套完成type值的替换。以下是具体实现:

function replaceTypes(item) {
  // 处理数组:遍历每个元素递归调用
  if (Array.isArray(item)) {
    return item.map(replaceTypes);
  }
  // 处理对象:先替换自身type,再递归处理属性值
  if (typeof item === 'object' && item !== null) {
    // 替换当前对象的type(存在对应映射时)
    if (item.type && types[item.type] !== undefined) {
      item.type = types[item.type];
    }
    // 遍历所有属性,递归处理嵌套结构
    for (const key in item) {
      if (Object.prototype.hasOwnProperty.call(item, key)) {
        replaceTypes(item[key]);
      }
    }
    return item;
  }
  // 非数组/对象类型直接返回
  return item;
}

// 调用函数处理目标数组
replaceTypes(obj);

// 查看处理结果
console.log(obj);

逻辑说明

  • 递归函数会自动识别当前处理的是数组还是对象:
    • 遇到数组就遍历每个元素,对每个元素重复执行处理逻辑
    • 遇到对象先检查并替换自身的type属性,再遍历对象的所有属性(比如示例里的options数组),继续递归处理深层嵌套
  • 这个方法支持任意层级的嵌套结构,不管是数组套对象还是对象套数组,都能覆盖到

处理后你的示例数据会变成:

[
  {
    type: 5,
    name: 'coolName',
    description: 'First description',
    required: false
  },
  {
    type: 1,
    name: 'destroy',
    description: 'Destroy something',
    options: [
      {
        type:4,
        name:"amount",
        description:"How much would you like to destroy?",
        required: true
      }
    ]
  }
]

如果不想修改原数组,而是生成新的结构,可以调整函数做深拷贝后再处理:

function replaceTypes(item) {
  if (Array.isArray(item)) {
    return item.map(replaceTypes);
  }
  if (typeof item === 'object' && item !== null) {
    // 深拷贝当前对象,避免修改原数据
    const newItem = {...item};
    if (newItem.type && types[newItem.type] !== undefined) {
      newItem.type = types[newItem.type];
    }
    for (const key in newItem) {
      if (Object.prototype.hasOwnProperty.call(newItem, key)) {
        newItem[key] = replaceTypes(newItem[key]);
      }
    }
    return newItem;
  }
  return item;
}

// 得到新的处理后数组,原数组保持不变
const newObj = replaceTypes(obj);

内容的提问来源于stack exchange,提问作者CheryX

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 01:15:11