简体   繁体   中英

Looking in deep nested object in React

My data looks like this:

let nodes= [{
    name: 'one',
    id: 1
    children: [{
        name: 'one-one',
        id: 11,
        children: [{
             name: 'one-one-one',
             id: 111,
             children: []
        },
        {
            name: 'one-one-two',
            id: 112,
            children: []
        }]
    },
    {
        name: 'one-two',
        id: 12,
        children: []
    }]
},
{
   name: 'two',
   id: 2,
   children: []
}];

I'm trying to do some actions on that object like finding an id or checking the value of each node. So far I accomplished to do so with a recursive function that is wrapped with a for loop but it looks sloppy and not the "react-way" to do that.

My function to find an Id looks like this:

findNodeById = (currNode, id) => {
        if (currNode.id === id) {
            return currNode;
        }

        if (currNode.hasOwnProperty('children')) {
            for (const i in currNode.children) {
                const foundNode = this.findNodeById(currNode.children[i], id);
                if (foundNode) {
                    return foundNode ;
                }
            }
        }

    return null;
};

for (const node in nodes) {
     const currNode= nodes[node],
           selectedValue = findNodeById(currNode, 12);

     if(selectedValue) {
         break;
     }
}

Isn't there a better and smarter way to do the same?

You shouldn't keep your data structured like this in the first place for exactly this reason. You should make your data structure flat by using ids as references to the actual objects. By using the ids of the nodes as keys in the nodes object, we can have O(1) performance.

let nodes= {
    '1': {
        name: 'one',
        id: 1,
        parent: null
        children: [11, 12],
    },
    '11': {
        name: 'one-one',
        id: 11,
        parent: 1,
        children: [111, 112],
    },
    '111': {
        name: 'one-one-one',
        id: 111,
        parent: 11,
        children: [],
    },
    '112': {
        name: 'one-one-two',
        id: 112,
        parent: 11,
        children: [],
    },
    '12': {
        name: 'one-two',
        id: 12,
        parent: 1,
        children: [],
    },
    '2' :{
        name: 'two',
        id: 2,
        parent: null,
        children: [],
    }
};

Now it becomes trivial to fetch a node or update a node in the list. However if you want to draw the tree to the screen, you would still need a way to convert the list into a tree. For this case, i would use a library such as: https://www.npmjs.com/package/performant-array-to-tree

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM