undefinedfix
Sign in

How to convert multiple arrays into tree structure and need to be de duplicated

piyushkantm edited in Tue, 17 Jan 2023

Examples: ['animal insect ant ','animal Insect Butterfly','plant grass green ','plant flower red']'Want to get: [{Name: 'animal', children:[

{name:'昆虫'
    children:[
        {name:'蚂蚁'},
        {name:'蝴蝶'}
    ]
}

]}, {ditto}]

3 Replies
user618075
commented on Tue, 17 Jan 2023
function listToTree (srcList) {
  let destList = []
  srcList.forEach(path => {
    let pathList = path.split('-')
    let levelList = destList
    for (let name of pathList) {
      let obj = levelList.find(item => item.name == name)
      if (!obj) {
        obj = { name, children: [] }
        levelList.push(obj)
      }
      levelList = obj.children
    }
  })
  return destList
}

Test:

let srcList =  ['动物-昆虫-蚂蚁', '动物-昆虫-蝴蝶', '植物-草-绿色', '植物-花-红色']
let result = listToTree(srcList)
console.log(JSON.stringify(result, null, 2))

Output:

[
  {
    "name": "动物",
    "children": [
      {
        "name": "昆虫",
        "children": [
          {
            "name": "蚂蚁",
            "children": []
          },
          {
            "name": "蝴蝶",
            "children": []
          }
        ]
      }
    ]
  },
  {
    "name": "植物",
    "children": [
      {
        "name": "草",
        "children": [
          {
            "name": "绿色",
            "children": []
          }
        ]
      },
      {
        "name": "花",
        "children": [
          {
            "name": "红色",
            "children": []
          }
        ]
      }
    ]
  }
]
Innuendo
commented on Tue, 17 Jan 2023
var arr = ['动物-昆虫-蚂蚁', '动物-昆虫-蝴蝶', '植物-草-绿色', '植物-花-红色']
var list = [], res = []
arr.forEach(child => {
  var items = child.split('-');
  var lis = {
    name: items[0],
    children: [{
      name: items[1],
      children: [{
        name: items[2]
      }]
    }]
  }
  list.push(lis);
})
list.forEach(lis => {
  handle(res, lis)
})
function handle (res, lis) {
  var curItem = res.find(item => item.name === lis.name)
  if (!curItem) {
    res.push(lis)
  } else {
    handle (curItem.children, lis.children[0])
  }
}
console.log(JSON.stringify(res, null, ' '));
fearhack
commented on Tue, 17 Jan 2023
var arr = ['动物-昆虫-蚂蚁', '动物-昆虫-蝴蝶', '植物-草-绿色', '植物-花-红色']
let newArr = [];
let getObjByName = function(arr,name){
    let newA = arr.filter(a => {
        return a.name === name;
    });
    let ret = {};
    if(newA.length === 0){
        ret = {children:[],name:name};
        arr.push(ret);
    } else {
        ret = newA[0];
    }
    return ret;
}
arr.forEach( ar => {
    let a = ar.split('-');
    let children1 = getObjByName(newArr,a[0]);
    let children2 = getObjByName(children1.children,a[0]);
    children2.children.push({name:a[2]});
    children2.name = a[1];
});

console.log(JSON.stringify(newArr, null, ' '));