需求:删除指定id相关的数据
let data = [
{ id: 1, parentId: "" },
{ id: 2, parentId: 1 },
{ id: 3, parentId: 1 },
{ id: 4, parentId: 2 },
{ id: 5, parentId: 2 },
{ id: 6, parentId: 4 },
{ id: 7, parentId: 5 }
];
比如删除2相关的数据,那么只剩下[{ id: 1, parentId: "" },{ id: 3, parentId: 1 }]
function deleteId(data, id) {
for (let i = data.length - 1; i >= 0; i--) {
if (data[i].parentId === id) {
const childrenId = data[i].id;
data.splice(i, 1);
deleteId(data, childrenId)
} else if (data[i].id === id) {
data.splice(i, 1)
}
}
}
deleteId(data, id)
console.log(data);
打印结果
[ { id: 1, parentId: '' }, { id: 3, parentId: 1 } ]
需求:找出指定id相关联的数据
function findId(data, id) {
this.deleteId = function (data, id) {
for (let i = data.length - 1; i >= 0; i--) {
if (data[i].parentId === id) {
const childrenId = data[i].id;
data.splice(i, 1);
this.deleteId(data, childrenId)
} else if (data[i].id === id) {
data.splice(i, 1)
}
}
return data
};
this.filterId = function (data, newData) {
return data.filter(item1 => newData.every(item2 => item2.id !== item1.id))
};
return this.filterId(data, this.deleteId([...data], id))
}
let test = findId(data, 2);
console.log('test', test);
打印
test [
{ id: 2, parentId: 1 },
{ id: 4, parentId: 2 },
{ id: 5, parentId: 2 },
{ id: 6, parentId: 4 },
{ id: 7, parentId: 5 }
]
网友评论