JS / VueJs / Vuetify-从JSON对象创建树

时间:2018-11-27 11:02:53

标签: javascript vue.js tree vuetify.js

我有一个非常大的JSON对象,我需要进入一棵树,但是我不确定该怎么做。我正在将VueJs与内置了Treeview的Vuetify一起使用,但我不知道如何为树准备好数据。

这是我的数据...

enter image description here

我需要的是(显然还没有包括所有数据)...

items: [
    {
        name: "Adboom",
        children: [
            {
                name: "Jaydox LTD",
                children: [
                    {
                        name: "beautifullyyoungskin.net"
                    },
                    {
                        name: "thinbodydiet.com"
                    },
                    {
                        name: "youthfulskincare.net"
                    }
                ]
            }
        ]
    },
    {
        name: "Adult",
        children: [
            {
                name: "Occonti Ltd",
                children: [
                    {
                        name: "datinginthe.eu (3d Secure)"
                    },
                    {
                        name: "datinginthe.eu (Non-3d)"
                    },
                    {
                        name: "datinginthe.eu - ST (Non-3d)"
                    },
                    {
                        name: "datinginthe.eu ST (3d Secure)"
                    }
                ]
            }
        ]
    }
]

1 个答案:

答案 0 :(得分:1)

您可以将一组键用于对象的所需嵌套分组,然后尝试查找具有所需级别值的name属性。

如果找到,请返回此项目,否则将其添加到children属性。

var data = [{ divisionName: "Adboom", merchantName: "Jaydox LTD", entityName: "beautifullyyoungskin.net" }, { divisionName: "Adboom", merchantName: "Jaydox LTD", entityName: "thinbodydiet.com" }, { divisionName: "Adboom", merchantName: "Jaydox LTD", entityName: "youthfulskincare.net" }, { divisionName: "Adult", merchantName: "Occonti Ltd", entityName: "datinginthe.eu (3d Secure)" }, { divisionName: "Adult", merchantName: "Occonti Ltd", entityName: "datinginthe.eu (Non-3d)" }, { divisionName: "Adult", merchantName: "Occonti Ltd", entityName: "datinginthe.eu - ST (Non-3d)" }, { divisionName: "Adult", merchantName: "Occonti Ltd", entityName: "datinginthe.eu ST (3d Secure)" }],
    keys = ["divisionName", "merchantName", "entityName"],
    result = data
        .reduce((r, o) => {
            keys.reduce((t, k) => {
                var temp = (t.children = t.children || []).find(p => p.name === o[k]);
                if (!temp) {
                    t.children.push(temp = { name: o[k] });
                }
                return temp;
            }, r);
            return r;
        }, {})
        .children;

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