本文介绍了Javascript使用object.create()从字符串构建树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从字符串(人的属性)创建服务树.我设法做到了,但是代码非常丑陋,这对我来说是实践的王,因为诀窍是我想使用"Object.create()"对象的类"来实现它,而该类将看起来像这样:

I'd like to create a tree of services from a string which are properties of people.I manage to do it, but the code is quite ugly, and it's a king of practice for me for the trick is i'd like to make it with "class" of objects using "Object.create()" where the class would look like this :

let service = {
        serviceFather: "",
        serviceChildren: [],
        people: [],
        }
    };

输入样本为:

[
  {
    "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"
  }
]

预期输出为:

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

推荐答案

您可以在service属性上使用split,然后使用forEach循环和reduce来迭代嵌套树并添加到数组中.

You could use split on service property and then forEach loop and reduce to iterate nested tree and add to array.

const 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" }
]

let service = {
  serviceFather: "",
  serviceChildren: [],
  people: [],
};

function create(data) {
  const res = []
  data.forEach(obj => {
    obj.service.split('.').reduce((r, e, i, a) => {
      const match = r.find(({ name }) => name == e);
      if(!match) {
        const o = Object.create(service);
        o.name = e;
        o.serviceFather = (i == 0 ? 'root' : a[i - 1])
        o.people = [{ name: obj.name }]
        o.serviceChildren = [];
        r.push(o)
        return r;
      } else {
        if(!a[i + 1]) match.people.push({ name: obj.name })
        return match.serviceChildren
      }
    }, res)
  })
  return res;
}

const result = create(data)
console.log(result)

这篇关于Javascript使用object.create()从字符串构建树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 02:35