I have the following object structure
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",
}
]
And I'm using the following code to add/remove/move which I took from 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)
But when I call this with the index paths. It moves file0 to folder02 instead of folder00 Is there a easier way to do this? I'm not sure how to insert by id as the index array also determines the order array.