Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a tree into an array?

I have a tree object which is an irregular tree which children's names and key values can change everytime I run my code. For example:

{
    addressRouter: 192.168.0.1,   
    addresses: 
        {
            address1: 'A',   

        },
        {
            address2: 'B',   

        },
        {
            ports: [
                {
                    portA: 'C',   
                    portB: null
                },


        }
    route: 'D',

}

so the names: 'addressRouter', 'addresses', 'address1', etc and their keys are unpredictable but I need to convert the tree object in arrays with the following format:

addressRouter
addresses/address1
addresses/address2
addresses/ports/portA
addresses/ports/portB
route

and then have their keys next to them.

I have this function to construct the tree, which is correct:

const iterate = (obj, obj2) => {
  Object.keys(obj).forEach(key => {

    obj2[key] = obj[key];

    if (typeof obj[key] === 'object') {
        iterate(obj[key], obj2)
    }
  })
}

but after debugging, I realized it doesn't get all branches.

like image 798
Natiya Avatar asked Dec 31 '22 16:12

Natiya


1 Answers

We can use a recursive function to traverse the tree and get the keys in the required format.

I am assuming addresses in the given tree object is an array of objects

function processTree(obj, rootKey) {
    const arr = [];
    obj && Object.keys(obj).forEach(key => {
        const val = obj[key];  
        if (val && val instanceof Array) {
            val.forEach(item => arr.push(...processTree(item, key)))
        }else if (val && typeof(val) == "object") {
            arr.push(...processTree(val, key));
        }else {
            arr.push(key);
        }
    });
    return rootKey ? arr.map(item => rootKey + "/" + item) : arr;
}

console.log(processTree(tree, null));

Result : ["addressRouter", "addresses/address1", "addresses/address2", "addresses/ports/portA", "addresses/ports/portB", "route"]

like image 117
Abito Prakash Avatar answered Jan 05 '23 16:01

Abito Prakash