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

JavaScript对象数组元素迁移:移除指定对象并移入新对象

JavaScript对象处理需求实现

需求说明

现有名为values的JavaScript对象,需完成以下操作:

  • 筛选c数组中满足条件的元素:元素的v字段为对象类型,且该子对象的f字段以空字符串开头
  • 将符合条件的元素从c数组中移除
  • 把该元素移入对象的CreateFileValue字段中

示例输入

const values = {
  ID: "",
  c: [{
      f: "",
      v: 'hello',
    },
    {
      f: "102",
      fi: "doc.pdf",
      v: {
        f: 'F2',
        fi: '',
        v: 'jkhkjhkhkjh'
      },
    }
  ]
}

修正后示例输出

注:原示例输出存在字段重复笔误,以下为符合需求的正确输出:

const values = {
  ID: 817,
  c: [{
      f: "F",
      v: 'hello',
    }
  ],
  CreateFileValue: {
    "f": "102",
    "fi": "doc.pdf",
    "v": {
      "f": 'F2',
      "fi": '',
      "v": 'jkhkjhkhkjh'
    }
  }
}

实现代码

const values = {
  ID: 7,
  c: [{
      f: "FL",
      v: 'hello',
    },
    {
      f: "F2",
      fi: "doc.pdf",
      v: {
        f: '',
        fi: '.pdf',
        v: 'jkhkjhkhkjh'
      },
    }
  ]
}

const processValues = () => {
  // 复制原对象避免直接修改原数据
  const result = { ...values, c: [...values.c] };
  
  // 查找符合条件的元素索引
  const targetIdx = result.c.findIndex(item => {
    return typeof item.v === 'object' && item.v !== null && item.v.f.startsWith('');
  });

  if (targetIdx !== -1) {
    // 移除目标元素并赋值给CreateFileValue
    const targetItem = result.c.splice(targetIdx, 1)[0];
    result.CreateFileValue = targetItem;
  }

  return result;
};

console.log(processValues());

代码说明

  • 数据复制:用扩展运算符复制原对象和数组,避免直接修改原数据;如需直接修改原对象可省略此步骤。
  • 条件判断:通过findIndex定位目标元素,判断逻辑为元素的v是对象且子对象v.f以空字符串开头;若实际需求是v.f为空字符串,可将startsWith('')改为=== ''。
  • 元素转移:用splice从数组中移除元素,再将其存入CreateFileValue字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 13:24:26