【发布时间】:2022-01-16 14:31:28
【问题描述】:
我有以下对象结构
layout: [
{
type: "FOLDER",
id: "folder0",
children: [
{
type: "FILE",
id: "file0",
},
{
type: "FOLDER",
id: "folder00",
children: [
{
type: "FILE",
id: "file7",
}
]
},
{
type: "FOLDER",
id: "folder02",
children: [
{
type: "FILE",
id: "file8",
}
]
}
]
},
{
type: "FOLDER",
id: "folder2",
children: [
{
type: "FILE",
id: "file4",
}
]
},
{
type: "FOLDER",
id: "folder1",
children: [
{
type: "FILE",
id: "file2",
},
{
type: "FILE",
id: "file3",
}
]
},
{
type: "FILE",
id: "file6",
}
]
我正在使用以下代码添加/删除/移动我从 this example 获取的代码
export const remove = (arr, index) => [
// part of the array before the specified index
...arr.slice(0, index),
// part of the array after the specified index
...arr.slice(index + 1)
];
export const removeChildFromChildren = (children, splitItemPath) => {
if (splitItemPath.length === 1) {
const itemIndex = Number(splitItemPath[0]);
return remove(children, itemIndex);
}
const updatedChildren = [...children];
const curIndex = Number(splitItemPath.slice(0, 1));
// Update the specific node's children
const splitItemChildrenPath = splitItemPath.slice(1);
const nodeChildren = updatedChildren[curIndex];
updatedChildren[curIndex] = {
...nodeChildren,
children: removeChildFromChildren(
nodeChildren.children,
splitItemChildrenPath
)
};
return updatedChildren;
};
export const insert = (arr, index, newItem) => {
console.log("insideinsert", arr, index, newItem)
return [
// part of the array before the specified index
...arr.slice(0, index),
// inserted item
newItem,
// part of the array after the specified index
...arr.slice(index)
];
}
export const addChildToChildren = (children, splitDropZonePath, item, targetid) => {
if (splitDropZonePath.length === 1) {
const dropZoneIndex = Number(splitDropZonePath[0]);
return insert(children, dropZoneIndex, item);
}
const updatedChildren = [...children];
const curIndex = Number(splitDropZonePath.slice(0, 1));
const splitItemChildrenPath = splitDropZonePath.slice(1);
const nodeChildren = updatedChildren[curIndex];
updatedChildren[curIndex] = {
...nodeChildren,
children: addChildToChildren(
nodeChildren.children,
splitItemChildrenPath,
item
)
};
return updatedChildren;
};
export const handleMoveToDifferentParent = (
layout,
splitDropZonePath,
splitItemPath,
item,
targetid
) => {
const removedfromlayout = removeChildFromChildren(layout, splitItemPath);
return addChildToChildren(
removedfromlayout,
splitDropZonePath,
item,
targetid
);
};
handleMoveToDifferentParent(layout, [0,2], [0,0], file0inobjectform)
但是当我用索引路径调用它时。它将 file0 移动到 folder02 而不是 folder00 有没有更简单的方法来做到这一点?我不确定如何按 id 插入,因为索引数组也决定了顺序数组。
【问题讨论】:
标签: javascript recursion multidimensional-array dynamic-arrays