Mig*_*ens 3 javascript ecmascript-6
我有一个递归函数,它通过id删除一个项目,如果该项目嵌套在children数组中,它也会将其向上移动一层,这基本上是一种菜单结构。删除项目后,子项不会被扔掉,而会留在原始对象中。
现在这需要一个“数据”参数并对其进行操作,但是 我想知道是否有可能将其转换为一个返回全新数组的函数,从而使参数保持不变?
这是功能
function removeId(data, id, parent = null) {
data.forEach((o, i) => {
if (o.id && o.id === id) {
if (parent) {
o.children.forEach(c => parent.children.push(c));
}
data.splice(i, 1);
return true;
} else if (o.children) {
removeId(o.children, id, o);
}
});
}
Run Code Online (Sandbox Code Playgroud)
这是使用的测试数据
const data = [
{
id: 2,
children: [
{
id: 1,
children: []
}
]
},
{
id: 3,
children: [],
}
]
Run Code Online (Sandbox Code Playgroud)
该函数这样调用
data = removeId(data, itemIdToDelete)
Run Code Online (Sandbox Code Playgroud)
预期的输出是一个具有前一个结构的新(不可变)数组,但除去的项(嵌套)除外
这是在运行方法并传递要删除的ID 2之后的预期输出
const data = [
{
id: 1,
children: []
},
{
id: 3,
children: [],
}
]
Run Code Online (Sandbox Code Playgroud)
编辑:这不仅是一个简单的深度克隆问题,还涉及逻辑,例如检查父母是否有孩子。
You could do this using reduce method and create new array on each level of recursion.
const data = [{"id":2,"children":[{"id":1,"children":[]}]},{"id":3,"children":[]}]
function removeId(data, id) {
return data.reduce((r, e) => {
// create shallow copy of the current object
const o = Object.assign({}, e);
// if object has children property
// create nested copy of children with recursive call
// where data param will now be children of the current element
if(e.children) {
o.children = removeId(e.children, id);
}
// if id of the current element is equal to target id
// push(spread) its children to current accumulator - r
// that will depend of the current recursion level
// else just push current object shallow copy - o
if (id == e.id) {
r.push(...o.children)
} else {
r.push(o)
}
// return accumulator
return r;
}, [])
}
console.log(removeId(data, 1))
console.log(removeId(data, 3))
console.log(removeId(data, 2))Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
135 次 |
| 最近记录: |