在父/子结构js中转换嵌套对象

时间:2019-11-22 12:56:33

标签: javascript tree

我尝试转换此结构(每个子对象都是对象中的属性):

const tree = {
  "Parent 1" : {
    "Children1": {
      "Children2": {
          "#1": { info: {}},
          "#2": { info: {}}.
          "#3": { info: {}}
    },
    "Children1-1": {
      "Children2-2": {
          "#1": { info: {}},
          "#2": { info: {}}.
          "#3": { info: {}}
    }
  },
  "Parent 2": {
  ...
   }
};

使用父子视图进入此树结构。但是到了树的尽头,我不需要孩子了

const resultTeee = [
  {
    name: 'Parent 1',
    children: [
      {
        name: 'Children 1',
        children: [
          {
            name: 'Children 2',
            children: [
              {name: "#1", info: {}},
              {name: "#2", info: {}}
            ]
          }
        ]
      },
      {
        name: 'Children 1-1',
        children: [
          {
            name: 'Children 2-2',
            children: [
              {name: "#1", info: {}},
              {name: "#2", info: {}}
            ]
          }
        ]
      }
    ]
  },
  {
    name: 'Parent 2'
    ....
  }
]

我尝试使用“遍历树”方法,但是不了解如何切换新的子路径。对象在每个级别上可以具有多个嵌套结构

1 个答案:

答案 0 :(得分:0)

const toArrayTree = (obj) => {
    return Object.keys(obj).map(key => {
        return {name: key, children: [toArrayTree(obj[key])]}
    })
}

测试对象

const tree = {
    "Parent 1" : {
        "Children1": {
            "Children2": {
                "#1": { info: {}},
                "#2": { info: {}},
                "#3": { info: {}},
            }
        },
    },
    "Parent 2" : {
        "Children2.1": {
            "Children2.2": {
                "#4": { info: {}},
                "#5": { info: {}},
                "#6": { info: {}},
            }
        },
    },
};

但是正如@adiga所说,为什么树的最后一个分支不是{ name: 'info', children: [] }

更新解决方案

const toArrayTree = (obj) => {
    return Object.keys(obj).map(key => {
        return typeof obj[key] === 'object' ?
            {name: key, children: [toArrayTree(obj[key])]} :
            {name: key, [key]: obj[key]};
    })
}

使用Object(v) === v确实是一个坏主意,因为对于v这样的函数来说确实如此