Javascript 如何从多层嵌套数组中删除对象并在JS中返回父数组?
我有以下嵌套数组,我需要删除id为47的fields对象并返回整个父数组。如何在JS中实现这一点Javascript 如何从多层嵌套数组中删除对象并在JS中返回父数组?,javascript,arrays,Javascript,Arrays,我有以下嵌套数组,我需要删除id为47的fields对象并返回整个父数组。如何在JS中实现这一点 [{ "id": 10, "name": "phone", "fields": [ { "id": 31, "name": "cellphone",
[{
"id": 10,
"name": "phone",
"fields": [
{
"id": 31,
"name": "cellphone",
"fields": [
{
"id": 47,
"name": "android"
}
]
},
{
"id": 32,
"name": "landline"
}
]
},
{
"id": 12,
"name": "document"
},
{
"id": 90,
"name": "document-name",
"fields": [
{
"id": 91,
"name": "new-name"
}
]
}]
我尝试了以下操作,但在使用过滤功能时出错
private getUpdatedData(data, id, searchKey = 'fields') {
data.forEach(function(ele) {
if(ele.id === id && ele[searchKey]) {
ele = ele[searchKey].filter(s => s.id === id);
} else if(ele.id === id && !ele[searchKey]) {
data = data.filter(s => s.id === id)
} else if(ele[searchKey]){
this.getUpdatedData(ele[searchKey], id, searchKey);
}
}.bind(this));
return data;
}
您可以通过使用递归过滤函数来实现
private getUpdatedData(data, id, searchKey = 'fields') {
data.forEach(function(ele) {
if(ele.id === id && ele[searchKey]) {
ele = ele[searchKey].filter(s => s.id === id);
} else if(ele.id === id && !ele[searchKey]) {
data = data.filter(s => s.id === id)
} else if(ele[searchKey]){
this.getUpdatedData(ele[searchKey], id, searchKey);
}
}.bind(this));
return data;
}
数据=[{
“id”:10,
“姓名”:“电话”,
“字段”:[
{
“id”:31,
“姓名”:“手机”,
“字段”:[
{
“id”:47,
“名称”:“安卓”
}
]
},
{
“id”:32,
“名称”:“固定电话”
}
]
},
{
“id”:12,
“名称”:“文件”
},
{
“id”:90,
“名称”:“文件名称”,
“字段”:[
{
“id”:91,
“名称”:“新名称”
}
]
}]
常量过滤器id=(数据,id)=>{
如果(!Array.isArray(数据))
返回数据
返回数据。筛选器(项=>{
if(项目中的“字段”)
item.fields=filterId(item.fields,id)
返回(item.id==未定义| | item.id!==id)
})
}
常量filtereddata=filterId(数据,47)
console.log(JSON.stringify(filterdata,null,4))
您可以使用splice
而不是filter从数组中删除对象
private getUpdatedData(data, id, searchKey = 'fields') {
data.forEach(function(ele) {
if(ele.id === id && ele[searchKey]) {
ele = ele[searchKey].filter(s => s.id === id);
} else if(ele.id === id && !ele[searchKey]) {
data.splice(0,1);
} else if(ele[searchKey]){
this.getUpdatedData(ele[searchKey], id, searchKey);
}
}.bind(this));
return data;
};
您的预期输出?在以下答案的帮助下完成。