How replace item in tree recursively

老子叫甜甜 提交于 2020-06-16 17:29:25

问题


I'm trying to create a tree. But I dont know how replace a item recursively inside a tree.

I have an array of items, each item if is on top parentId is undefined and if has clindren, each children has a parentId property that show how is his parent.

I'm trying to create a method that find that item inside children property, who can have 1 or more levels.

And if its possible return updated array

This is my code:

const onChangeStatusEditable = () => {
    const updatedBranch: IBranch = Object.assign({}, branch, {
        editable: !editable,
    });
    let updatedBranchs: Array<IBranch> = [];
    if (parentId === undefined) {
        const index = branchs.findIndex( (b: IBranch) => b.id === branch.id);
        updatedBranchs = Object.assign([], branchs, {
            [index]: updatedBranch,
        });
        onUpdateBranchs(updatedBranchs);
    } else {
        // EDIT: efforts 
        I'm tryin with this recursive method
    }
};
// EDIT
export const replaceBranch = (branchs: Array<IBranch>, branch: IBranch): Array<IBranch> => {
    let updated: Array<IBranch> = [];
    branchs.forEach((b: IBranch) => {
        if (b.children) {
            updated = replaceBranch(b.children, branch);
            if (updated) {
                return updated;
            }
        }
        if (b.id === branch.id) {
            const index: number = branchs.findIndex((c: IBranch) => c.id === branch.id);
            b.children[index] = branch;
            updated = b.children;
            console.log("founded: ", b);
            return updated;
        }
    });
    return updated;
};

And IBrach has this interface:

export interface IBranch {
    id: number;
    parentId: number | undefined;
    active: boolean;
    favorite: boolean;
    title: string;
    editable: boolean;
    level: number;
    checkbox: boolean;
    checkboxEnabled: boolean;
    children: Array<any>;
}

Data:

[
   {
      "id":0,
      "active":false,
      "favorite":false,
      "level":0,
      "title":"New Branch 0",
      "editable":false,
      "checkbox":false,
      "checkboxEnabled":false,
      "children":[
         {
            "id":1,
            "parentId":0,
            "active":false,
            "favorite":false,
            "level":1,
            "title":"New Branch 1",
            "editable":false,
            "checkbox":false,
            "checkboxEnabled":false,
            "children":[

            ]
         }
      ]
   }
]


回答1:


I think you can do a fairly simple recursion here. I test with a very minimal set of data. Nodes have ids, titles, and sometimes children. But I think that's enough to show the behavior.

const updateElement = (obj, el) => 
  Array .isArray (obj) 
    ? obj .map (o => updateElement (o, el))
  : obj .id === el .id 
    ?  el
  : // else
    {...obj, ...(obj .children ? {children: updateElement (obj .children, el)} : {})}

const data = [
  {id: 1, title: 'foo', children: [
    {id: 11, title: 'bar'},
    {id: 12, title: 'baz', children: [
      {id: 121, title: 'qux'},
      {id: 122, title: 'quz'}
    ]},
    {id: 13, title: 'corge'}
  ]},
  {id: 2, title: 'grault'}
];

const newItem = {id: 121, title: 'new title here', and: 'more props'}

console .log (
  updateElement (data, newItem)
)
.as-console-wrapper {min-height: 100% !important; top: 0}

Note that this code doesn't stop searching on the first match. It checks everything and replaces all matches. I don't know if that's acceptable behavior for you.

This version is written in plain Javascript. I leave the Typescript typings to you. (Because I certainly don't want to do them!)



来源:https://stackoverflow.com/questions/62174052/how-replace-item-in-tree-recursively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!