首先,您需要一些健壮的类型:
interface Folder {
id: string
name: string
files: FileItem[]
}
interface FileItem {
id: string
name: string
}
现在我们可以在这里使用文件夹数组作为类型来代替List:
let list: Folder[] = [...]
为了让参数更清晰,让我们将它们重命名为更清晰的东西:
function move(
list: Folder[],
fileId: string,
destinationFolderId: string
): Folder[] {
//...
}
现在很清楚第二个参数是文件的ID,第三个参数是文件夹的ID。
然后找到文件,将其从文件夹中删除,然后将其添加到新文件夹中,这是一件非常简单的事情:
function move(list: Folder[], fileId: string, destinationFolderId: string): Folder[] {
// Variable to store the found file, once it is found.
let file: FileItem | undefined
// Loop through each folder looking a file with the right ID
for (const folder of list) {
// Look for the correct file in this folder.
file = folder.files.find(file => file.id === fileId)
// If a file was found in this folder...
if (file) {
// Remove it from this folder
folder.files = folder.files.filter(otherFile => otherFile.id !== fileId)
// Stop looping, there is nothing else to do.
break
}
}
// Find the destination folder by its ID.
const destinationFolder = list.find(folder => folder.id === destinationFolderId)
// If file was found, and a desination folder was found...
if (file && destinationFolder) {
// Add the file to the new destination folder.
destinationFolder.files.push(file)
}
// Return the updated folder list
return list
}
Playground
请注意,此函数变异 list 作为副作用。这可能是您想要的,也可能不是。如果您希望在不更改传入的对象的情况下返回新对象,则需要查看immutable strategies。