Home > Software engineering >  convert object to array with hierarchy
convert object to array with hierarchy

Time:04-26

const obj = {
  a: {
    ab: {
      abc: {},
      abd: {},
    },
    ac: {
      acd: {},
    }
  },
  b: {
    bc: {
      bcd: { bcde: {} },
    },
    bd: {},
  }
}

// What I expected
/*
const expected = [
  { 
    name: 'a', 
    children: [{
      name: 'ab',
      children: [{
        name: 'abc',
        children: [],
      }, {
        name: 'abd',
        children: [],
      }],
    }],
  },
  { 
    name: 'b', 
    children: [{
      name: 'bc',
      children: [{ name: 'bcde', children: [] }],
    }, {
      name: 'bd',
      children: [],
    }]
  },
]
*/

I guess I can achieve it with a recursive function but now my brain doesn't work...

CodePudding user response:

you can try with the function .push(), you will get the format request. array.push(name:"VARIABLE WITH THE NAME", childred:"VARIABLE WITH THE CHILDREN").

CodePudding user response:

Something like this

const obj = {
  a: {
    ab: {
      abc: {},
      abd: {},
    },
    ac: {
      acd: {},
    }
  },
  b: {
    bc: {
      bcd: { bcde: {} },
    },
    bd: {},
  }
}

const group = data => {
  if(Object.keys(data).length === 0){
     return []
  }
  return Object.entries(data).map(([k, v]) => {
    return {
     name: k,
     children: group(v)
    }
  })
}

console.log(group(obj))

CodePudding user response:

Hope, this will help you :)

const obj = {
  a: {
    ab: {
      abc: {},
      abd: {},
    },
    ac: {
      acd: {},
    }
  },
  b: {
    bc: {
      bcd: { bcde: {} },
    },
    bd: {},
  }
}

function isObj(obj) {
    return typeof obj === 'object' &&
    !Array.isArray(obj) &&
    obj !== null
}

function objToArray(obj) {
    let res = [];
  
  for (const [key, value] of Object.entries(obj)) {
    let child = { name: key, children: isObj(obj)
        ? objToArray(value) : [] };
    
    res.push(child);
  }
  
  return res;
}

console.log(objToArray(obj));

  • Related