1

I am having JSON in the form of {"Others": null, "Main Hobbies": {"Dance": ["Salsa", "Solo"], "Sports": ["Cricket"]}, "Game": ["PUBG", "Cricket", "Football"]} '

And i want to convert it into tree structure like

 data =   [
// not include Others since it is null
{ name: 'Main Hobbies',
  checked: false,
  children: [
      { name: 'Dance', checked: false, children: [ { name: 'Salsa', checked: false },{ name: 'Solo', checked: false }] },
      { name: 'Sports' , checked : false , children [{name :'Cricket',checked:false}]}
  ]
},
{ name: 'Game', checked: false ,children:[{name:"PUBG",checked:false},{name:"Cricket",checked:false},{name:"Football",checked:false}]},

Here is how i am using these below functions so far , but rather than converting it to tree structure it is converting into list structure i.e upto only two levels.However the desired output is of Three level

let data = {"Others": null, "Main Hobbies": {"Dance": ["Salsa", "Solo"], "Sports": ["Cricket"]}, "Game": ["PUBG", "Cricket", "Football"]};
var result = filterData(data);
function filterData(data){
    let result = [];
    for (var key in data){
      var value = data[key];
      let val = data[key];
      if(val){
        if(Array.isArray(val) && val.length>0){
          let ob ={};
          ob['name'] = key;
          ob['checked']=false;
          ob['children'] = getChildren(val);   
          result.push(ob);  
       }else if(typeof val == 'object'){
         let ob ={};
         ob['name'] = key;
         ob['checked']=false;
         ob['chldren']=filterData(val);
         result.push(filterData(val));
       }
    
     }
    }
    return result;
  }
  function getChildren(data){
    let result = [];
    data.forEach(function(e){
      let ob = {};
      ob['name'] = e;
      ob['checked']=false;
       if(Array.isArray(e.children) && e.children.length){
           ob['children'] = getChildren(e.children);
         }
       result.push(ob);  
    })
    return result;
  
    
  }
  console.log(result);

 ];

want to convert tree nodes like here

1 Answer 1

2

You could take a recursive approach for objects by checking the type of the handed over data.

function create(data, checked = false) {
    return Array.isArray(data)
        ? data.map(name => ({ name, checked }))
        : Object
            .entries(data)
            .filter(([, v]) => v !== null && (!Array.isArray(v) || v.length))
            .map(([name, value]) => ({
                name,
                checked,
                children: create(value, checked)
            }))
}

var data = { empty: [], Others: null, "Main Hobbies": { Dance: ["Salsa", "Solo"], Sports: ["Cricket"] }, Game: ["PUBG", "Cricket", "Football"] },
    result = create(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

6 Comments

your mind in now hard-wired to do this stuff in half of a second :D
@Nina Scholz working fine , plz do me a fever like how do handle the case for [] similar to null
@NinaScholz what if i want to consider Null as well tried return Array.isArray(data) ? data.map(name => ({ name, checked })) : Object .entries(data).map(([name, value]) => ({ name, checked, children: create(value, checked) })) but it is not working
so for this case { name: 'Others', checked: false}
then you need this part: .filter(([, v]) => !Array.isArray(v) || v.length) .map(([name, value]) => value === null ? { name, checked } : { name, checked, children: create(value, checked) } )
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.