从数组创建对象树

时间:2019-04-15 21:04:54

标签: javascript arrays object tree reduce

我想用数组制作一棵对象树。 这里提供了一个很好的解决方案(我发现“减少”方法的地方):Javascript build a tree from a string with object.create() 实际上,我的需求有所不同,并且我无法调整所提供的代码...所以我回到这里寻求帮助! (谢谢)。 我将在本文结尾处张贴完整的初始代码

输入:

[
  {
    "name": "John Doe",
    "service": "EE",
  },
  {
    "name": "Jane Doe",
    "service": "EE.EA",
  },
  {
    "name": "Jack Smith",
    "service": "EE.EA.EB",
  },
  {
    "name": "Jill Smith",
    "service": "EE.EA.EC"
  },
  {
    "name": "Jake Smith",
    "serviceLevel": "EE.EA.EC"
  }
]

输出:

{
    "EE":
    {
        "serviceFather": "root",
        "people": [
        {
            "name": "John Doe"
        }],
        "serviceChildren":
        {
            "EA":
            {
                "serviceFather": "EE",
                "people": [
                {
                    "name": "Jane Doe"
                }],
                "serviceChildren":
                {
                    "EB":
                    {
                        "serviceFather": "EA",
                        "people": [
                        {
                            "name": "Jack Smith"
                        }],
                        "serviceChildren":
                        {}
                    },
                    "EC":
                    {
                        "serviceFather": "EA",
                        "people": [
                        {
                            "name": "Jill Smith"
                        },
                        {
                            "name": "Jake Smith"
                        }],
                        "serviceChildren":
                        {}
                    }
                }
            }
        }
    }
}

初始代码:

function format(data) {
    const res = []
    data.forEach(obj => {
        obj.serviceTree.split('.').reduce((r, e, i, a) => {
            console.log(r, e, i, a);
            const oParent = r.find(({ name }) => name == a[i - 1]);
            const match = r.find(({ name }) => name == e);
            if (!match) {
                const o = Object.create(service);
                o.name = e;
                if (!a[i + 1]) {
                    o.serviceName = obj.serviceName;
                    o.serviceTree = obj.serviceTree;
                    o.serviceLevel = i;
                    o.serviceParent = (i == 0 ? 'root' : a[i - 1]);
                    o.people = [{
                        familyName: obj.familyName,
                        firstName: obj.firstName,
                        jobTitle: obj.jobTitle,
                        rank: obj.rank,
                        phone: obj.phone,
                        mobile: obj.mobile,
                        mail: obj.mail
                    }];

                    if (oParent) {
                        oParent.serviceChildren.push(o);
                    } else {
                        o.serviceChildren = [];
                        r.push(o);
                    }

                } else {
                    let treeStamp = a.slice();
                    treeStamp.pop();
                    o.serviceName = e;
                    o.serviceTree = treeStamp.join('.');
                    o.serviceLevel = i;
                    o.serviceParent = (i == 0 ? 'root' : a[i - 1]);
                    o.serviceChildren = [];
                    r.push(o);
                }
                return r;

            } else {
                if (!a[i + 1]) match.people.push({
                    familyName: obj.familyName,
                    firstName: obj.firstName,
                    jobTitle: obj.jobTitle,
                    rank: obj.rank,
                    phone: obj.phone,
                    mobile: obj.mobile,
                    mail: obj.mail
                });
                return match.serviceChildren;
            }
        }, res);
    });
    return res;
}

2 个答案:

答案 0 :(得分:2)

您可以使用拆分服务的一部分,并将其作为访问嵌套对象的键。

var data = [{ name: "John Doe", service: "EE" }, { name: "Jane Doe", service: "EE.EA" }, { name: "Jack Smith", service: "EE.EA.EB" }, { name: "Jill Smith", service: "EE.EA.EC" }, { name: "Jake Smith", service: "EE.EA.EC" }],
    result = {};

data.forEach(({ name, service }) => {
    service
        .split('.')
        .reduce((o, k, i, { [i - 1]: serviceFather = 'root' }) => {
            o.serviceChildren = o.serviceChildren || {};
            o.serviceChildren[k] = o.serviceChildren[k] || { serviceFather, people: []  };
            return o.serviceChildren[k];
        }, { serviceChildren: result })
        .people.push({ name });
});

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

答案 1 :(得分:1)

给出的代码过于复杂。可能很简单:

 const root = { name: "root", serviceChildren: {} };

 for(const { name, service } of input) {
    let acc = root;
    for(const key of service.split(".")) {
       if(!acc.serviceChildren[key]) {
         acc.serviceChildren[key] = {
           name: key,
           serviceFather: acc.name,
           serviceChildren: {},
           people: [],
        };
      }
     acc = acc.serviceChildren[key];
    }

    acc.people.push({ name });
 }

 const output = root.serviceChildren;