简体   繁体   English

在父/子结构js中转换嵌套的object

[英]convert nested object in parent / children structure js

I try to convert this structure (each child is property in object):我尝试转换此结构(每个孩子都是对象中的属性):

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

In to this tree structure with parent child view.在这个带有父子视图的树结构中。 But in the end of my tree i don't need childrens但在我的树的尽头,我不需要孩子

 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'.... } ]

I try "traverse tree" approach but can't understand how to switch for new children path.我尝试“遍历树”方法,但不明白如何切换到新的子路径。 Object can have multiple nested structure on each level. Object 在每一层上可以有多个嵌套结构

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

object for testing object 用于测试

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

But as @adiga said, why the last branch of tree is not { name: 'info', children: [] } ?但正如@adiga 所说,为什么树的最后一个分支不是{ name: 'info', children: [] }

Update on solution解决方案更新

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]};
    })
}

It's really bad idea to use Object(v) === v , because it would be true for v being function for example使用Object(v) === v确实是个坏主意,因为例如 v 是 function

You could map the entries of the object.您可以mapentries If the value is an object, recursively call the function.如果值为 object,则递归调用 function。

 const tree = {"Parent 1":{Children11:{Children111:{"#1":{info:{}},"#2":{info:{}},"#3":{info:{}}}}},"Parent 2":{Children21:{Children211:{"#1":{info:{}},"#2":{info:{}},"#3":{info:{}}}}}}; function trasnform(o) { return Object.entries(o).map(([name, v]) => Object(v) === v? { name, children: trasnform(v) }: { name, value: v } // unclear from the question ) } console.log(trasnform(tree))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM