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

如何在同数组的对象间移动子对象?TypeScript实现问题

文件移动函数问题解决思路

需求说明

我有一个move函数,包含list、source、destination三个参数:

  • list是文件夹数组,每个文件夹包含id、name和files(文件数组,每个文件有id和name)
  • 调用move(list, '4', '6')时,需要将id为'4'的文件从原文件夹移动到id为'6'的文件夹中

输入示例

const list = [
      {
        id: '1',
        name: 'Folder 1',
        files: [
          { id: '2', name: 'File 1' },
          { id: '3', name: 'File 2' },
          { id: '4', name: 'File 3' },
          { id: '5', name: 'File 4' },
        ],
      },
      {
        id: '6',
        name: 'Folder 2',
        files: [{ id: '7', name: 'File 5' }],
      },
    ];

期望输出

const result = [
  {
    id: '1',
    name: 'Folder 1',
    files: [
      { id: '2', name: 'File 1' },
      { id: '3', name: 'File 2' },
      { id: '5', name: 'File 4' },
    ],
  },
  {
    id: '6',
    name: 'Folder 2',
    files: [
      { id: '7', name: 'File 5' },
      { id: '4', name: 'File 3' },
    ],
  },
];

当前代码问题

我现在能将目标文件添加到目标文件夹,但无法删除原位置的文件,当前TypeScript代码如下:

let copyList = list.slice();

const filteredVal = copyList[0].files.find((file: { id: Object; })=> { 
  return file.id == source
} );

// 尝试删除但无效的代码
// if (copyList[0].files.id === source){
//   delete copyList[0].files.source
// }

copyList[1].files.push(filteredVal);

return copyList[1]

解决步骤与替代思路

  • 不要硬编码文件夹索引(比如copyList[0]),先遍历list找到源文件所在的文件夹(查找哪个文件夹的files数组包含id为source的文件)和目标文件夹(通过id匹配destination)
  • 移除原位置文件的两种方案:
    • 使用filter方法:给源文件夹的files重新赋值为过滤后的数组,排除id等于source的文件,这种方式会生成新数组,避免直接修改原引用
    • 使用findIndex找到源文件在数组中的索引,再用splice(index, 1)删除对应元素
  • 注意引用类型问题:slice()只是浅拷贝,要确保修改的是文件夹和文件数组的副本,避免污染原始list,可以用对象展开语法({...folder, files: [...folder.files]})来创建新的文件夹对象
  • 函数最后返回修改后的完整copyList,而不是只返回目标文件夹

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:01:53