如何解决重建一个深层嵌套的对象数组,删除不需要的对象
我不知道如何在通过 id 值指向它的深嵌套对象数组中删除和对象。
这是我使用 reduce 的代码。我想在每次迭代时重新创建数组,因为它很混乱(而且它只通过索引 0)。
我想通过指向节点 ID 35993 来删除整个部分。 如果节点获得一个子节点,这也会删除子节点。
const array = [
{
node: {
level: 0,id: 71,type: "block",style: {
backgroundColor: "#548444",},children: [
{
node: {
id: 85,style: {
backgroundColor: "#548444",fontSize: "19px",children: [
{
node: {
id: 955,type: "column",style: {
backgroundColor: "#eee",fontSize: "28px",children: [
{
node: {
level: 3,parentId: 71,id: 732,type: "text",data: {
text: "Ceci est un text",style: {
color: "blue",fontSize: "13px",{
node: {
id: 353,],{
node: {
level: 0,id: 7991,children: [
{
node: {
id: 8995,children: [
{
node: {
id: 95995,id: 73992,{
node: {
id: 35993,];
const search1 = (arr,itemId,nestingKey) =>
arr.reduce((a,item) => {
if (a) return a;
if (item.node.id === itemId) return item;
if (item[nestingKey]) return search(item[nestingKey],nestingKey);
},null);
const remove = function (arr,nestingKey) {
let newArr = [];
arr.reduce((a,item) => {
if (item.node.id !== itemId) {
const tempItem = {
...item,};
newArr.push(tempItem);
}
if (item.node.id === itemId) {
delete item.node;
return item;
}
if (item[nestingKey]) return remove(item[nestingKey],null);
return newArr;
};
const res = remove(array,35993,"children");
console.log(JSON.stringify(res));
解决方法
在这里修改数组非常容易,无论如何您都不必担心删除子项,因为您删除了项目的一部分。只需找到要移除的数组项,然后拼接出来即可。
即使你不想要一个变异的数组,克隆/复制并仍然这样做可能会更容易。
示例如下。 我已经使用 id 95995 显示它也在删除孩子..
const array = [{"node":{"level":0,"id":71,"type":"block","style":{"backgroundColor":"#548444"}},"children":[{"node":{"id":85,"style":{"backgroundColor":"#548444","fontSize":"19px"}},"children":[{"node":{"id":955,"type":"column","style":{"backgroundColor":"#eee","fontSize":"28px"}},"children":[{"node":{"level":3,"parentId":71,"id":732,"type":"text","data":{"text":"Ceci est un text"},"style":{"color":"blue","fontSize":"13px"}}},{"node":{"id":353,"fontSize":"13px"}}}]}]}]},{"node":{"level":0,"id":7991,"children":[{"node":{"id":8995,"children":[{"node":{"id":95995,"id":73992,{"node":{"id":35993,"fontSize":"13px"}}}]}]}]}];
function removeById(array,id) {
for (let ix = 0; ix < array.length; ix += 1) {
const r = array[ix];
if (r.node.id === id) {
array.splice(ix,1);
} else {
if (r.children) removeById(r.children,id);
}
}
}
console.log(JSON.stringify(array));
removeById(array,95995);
console.log(JSON.stringify(array));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。