gpt4 book ai didi

javascript - 从动态创建的 ObjectArray 中删除一个对象

转载 作者:行者123 更新时间:2023-11-29 19:05:44 24 4
gpt4 key购买 nike

我有一个对象数组像这样的列表格式

var myFormData = [
{
id: 1,
name: "first name",
type: "test",
root: "/myfolder"
},
{
id: 3,
name: "your name",
type: "test 2",
root: "/myfolder2"
}, {
id: 4,
name: "your test",
type: "test 3",
root: "/myfold",
child: [
{
id: 5,
name: "name",
type: "testf",
root: "/myfoldertr"
},
{
id: 6,
name: "first-name",
type: "test",
root: "/myfolderoot",
child: [
{
id: 8,
name: "sub first name",
type: "test5",
root: "/myfoldertest"
}, {
id: 9,
name: "first name root",
type: "test9",
root: "/myfolder",
child: [
{
id: 10,
name: "normal first name",
type: "test5",
root: "/myfoldertest"
}, {
id: 11,
name: "last first name",
type: "test5",
root: "/myfoldertest"
}
]
},
{
id: 12,
name: "name Name",
type: "testf",
root: "/myfoldertr"
}
]
},
{
id: 7,
name: "first name",
type: "test",
root: "/myfolder"
}
]
}]

这种格式是用数据库创建的,所以我不能保证数据是准确的。有时他们是否有 child 。如果 id 等于给定的 id(以编程方式获取),我想删除一个对象,例如:我想删除 id=11。

最佳答案

关键是您必须深入查看目标数组。此代码片段示例使用递归调用深入嵌套数组。

function deleteObj(target, id) {
if (!Array.isArray(target)) return;
target.forEach(function(item, index) {
if (item.child) {
target = deleteObj(item.child, id);
}
if (item.id === 11) {
target.splice(index, 1);
}
});
}

var myFormData = [{
id: 1,
name: "first name",
type: "test",
root: "/myfolder"
},
{
id: 3,
name: "your name",
type: "test 2",
root: "/myfolder2"
}, {
id: 4,
name: "your test",
type: "test 3",
root: "/myfold",
child: [{
id: 5,
name: "name",
type: "testf",
root: "/myfoldertr"
},
{
id: 6,
name: "first-name",
type: "test",
root: "/myfolderoot",
child: [{
id: 8,
name: "sub first name",
type: "test5",
root: "/myfoldertest"
}, {
id: 9,
name: "first name root",
type: "test9",
root: "/myfolder",
child: [{
id: 10,
name: "normal first name",
type: "test5",
root: "/myfoldertest"
}, {
id: 11,
name: "last first name",
type: "test5",
root: "/myfoldertest"
}]
},
{
id: 12,
name: "name Name",
type: "testf",
root: "/myfoldertr"
}
]
},
{
id: 7,
name: "first name",
type: "test",
root: "/myfolder"
}
]
}
];

function deleteObj(target, id) {
if (!Array.isArray(target)) return;
target.forEach(function(item, index) {
if (item.child) {
target = deleteObj(item.child, id);
}
if (item.id === 11) {
target.splice(index, 1);
}
});
}

deleteObj(myFormData, 11);
console.log(myFormData);

关于javascript - 从动态创建的 ObjectArray 中删除一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43012569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com