从Typescript / JavaScript中的平面数组构建树数组

时间:2019-11-21 16:19:54

标签: javascript angular typescript

我有一个复杂的json文件,必须使用TypeScript / Javascript处理才能使其具有层次结构,以便以后构建调查表。 json的每个条目都有一个ID(唯一),ParentId(如果为root,则为0),文本,描述。

我的打字稿界面

export interface Question {
    Id: number;
    Text: string;
    Desc: string;
    ParentId: number;
    ChildAnswers?: Answer[];
}

export interface Answer {
    Id: number;
    Text: string;
    Desc: string;
    ParentId: number;
    ChildQuestion?: Question;
}

我可以保证,当对象是答案时,只会有一个孩子,我们可以认为这是一个问题。

平面数据示例:

[
{
    Id: 1,
    Text: 'What kind of apple is it?',
    Desc: '',
    ParentId: 0
},
{
    Id: 2,
    Text: 'Green Apple',
    Desc: '',
    ParentId: 1
},
{
    Id: 3,
    Text: 'Red Apple',
    Desc: '',
    ParentId: 1
},
{
    Id: 4,
    Text: 'Purple GMO Apple',
    Desc: '',
    ParentId: 1
},
{
    Id: 5,
    Text: 'What is the issue with the apple?',
    Desc: '',
    ParentId: 2
},
{
    Id: 6,
    Text: 'Spoiled.',
    Desc: '',
    ParentId: 5
},
{
    Id: 7,
    Text: 'Taste Bad.',
    Desc: '',
    ParentId: 5
},
{
    Id: 8,
    Text: 'Too Ripe.',
    Desc: '',
    ParentId: 5
},
{
    Id: 9,
    Text: 'Is not an apple.',
    Desc: '',
    ParentId: 5
},
{
    Id: 10,
    Text: 'The apple was not green.',
    Desc: '',
    ParentId: 5
},
... So on ...
]

我的目标

{
    Id: 1,
    Text: 'What kind of apple is it?',
    Desc: '',
    ParentId: 0,
    ChildAnswers: [
        {
            Id: 2,
            Text: 'Green Apple',
            Desc: '',
            ParentId: 1,
            ChildQuestion: {
                Id: 5,
                Text: 'What is the issue with the apple?',
                Desc: '',
                ParentId: 2,
                ChildAnswers: [
                    {
                        Id: 6,
                        Text: 'Spoiled.',
                        Desc: '',
                        ParentId: 5,
                        ... So on ...
                    },
                    {
                        Id: 7,
                        Text: 'Taste Bad.',
                        Desc: '',
                        ParentId: 5,
                        ... So on ...
                    },
                    {
                        Id: 8,
                        Text: 'Too Ripe.',
                        Desc: '',
                        ParentId: 5,
                        ... So on ...
                    },
                    {
                        Id: 9,
                        Text: 'Is not an apple.',
                        Desc: '',
                        ParentId: 5,
                        ... So on ...
                    },
                    {
                        Id: 10,
                        Text: 'The apple was not green.',
                        Desc: '',
                        ParentId: 5,
                        ... So on ...
                    },
                    ... So on ...
                ]
            }
        },
        {
            Id: 3,
            Text: 'Red Apple',
            Desc: '',
            ParentId: 1,
            ... So on ...
        },
        {
            Id: 4,
            Text: 'Red Apple',
            Desc: '',
            ParentId: 1,
            ... So on ...
        }
        ... So on ...
    ]
}

我目前正在使用在stackoverflow上找到的list_to_tree函数,我只是不知道如何区分问题和答案。我应该检查一下问题的长度是否为一个或以奇数的间隔标记它?:

function list_to_tree(list) {
    var map = {}, node, roots = [], i;
    for (i = 0; i < list.length; i += 1) {
        map[list[i].Id] = i; // initialize the map
        list[i].Children = []; // initialize the children
    }
    for (i = 0; i < list.length; i += 1) {
        node = list[i];
        if (node.ParentId !== 0) {
            // if you have dangling branches check that map[node.ParentId] exists
            list[map[node.ParentId]].Children.push(node);
        } else {
            roots.push(node);
        }
    }
    return roots;
}

3 个答案:

答案 0 :(得分:2)

以下是该问题的蛮力解决方案:

var flat = [
{
    Id: 1,
    Text: 'What kind of apple is it?',
    Desc: '',
    ParentId: 0
},
{
    Id: 2,
    Text: 'Green Apple',
    Desc: '',
    ParentId: 1
},
{
    Id: 3,
    Text: 'Red Apple',
    Desc: '',
    ParentId: 1
},
{
    Id: 4,
    Text: 'Purple GMO Apple',
    Desc: '',
    ParentId: 1
},
{
    Id: 5,
    Text: 'What is the issue with the apple?',
    Desc: '',
    ParentId: 2
},
{
    Id: 6,
    Text: 'Spoiled.',
    Desc: '',
    ParentId: 5
},
{
    Id: 7,
    Text: 'Taste Bad.',
    Desc: '',
    ParentId: 5
},
{
    Id: 8,
    Text: 'Too Ripe.',
    Desc: '',
    ParentId: 5
},
{
    Id: 9,
    Text: 'Is not an apple.',
    Desc: '',
    ParentId: 5
},
{
    Id: 10,
    Text: 'The apple was not green.',
    Desc: '',
    ParentId: 5
},
]

// first get the roots
const tree = flat.filter((question) => question.ParentId === 0);

// Next we are going to call alternating methods recursively.
function populateQuestionChildren(node) {
  const { Id } = node;
  flat.forEach((answer) => {
    if (answer.ParentId === Id) {
      if (!node.ChildAnswers) {
        node.ChildAnswers = [];
      }
      node.ChildAnswers.push(answer);
      populateAnswerChildren(answer);
    }
  });
}

function populateAnswerChildren(node) {
  const { Id } = node;
  flat.forEach((question) => {
    if (question.ParentId === Id) {
      if (!node.ChildQuestions) {
        node.ChildQuestions = [];
      }
      node.ChildQuestions.push(question);
      populateQuestionChildren(question);
    }
  });
}

// Kick off the build for each question tree. 
tree.forEach((question) => {
  populateQuestionChildren(question);
});

可能会有更优雅的解决方案-但是鉴于这将只有几十个或几百个问题/答案-这应该可以为您提供所需的信息。

[编辑]

我使用了您的界面,发现我的代码有问题。 Answer对象上只有一个“ ChildQuestion”。因此,这是我对TypeScript所做的更改,以使其正常工作。希望对您有所帮助:


interface Question {
  Id: number;
  Text: string;
  Desc: string;
  ParentId: number;
  ChildAnswers ? : Answer[];
}

interface Answer {
  Id: number;
  Text: string;
  Desc: string;
  ParentId: number;
  ChildQuestion ? : Question;
}

// first get the roots
const tree = flat.filter((question) => question.ParentId === 0);

function populateQuestionChildren(node: Question) {
  const { Id } = node;
  flat.forEach((answer) => {
    if (answer.ParentId === Id) {
      if (!node.ChildAnswers) {
        node.ChildAnswers = [];
      }
      node.ChildAnswers.push(answer);
      populateAnswerChild(answer);
    }
  });
}

function populateAnswerChild(answer: Answer) {
  const { Id } = answer;
  // switch to every so we can break early once a question is found.
  flat.every((node) => {
    if (node.ParentId === Id) {
      answer.ChildQuestion = node;
      populateQuestionChildren(node);
      return false;
    }
    return true;
  });
}

tree.forEach((question) => {
  populateQuestionChildren(question);
});

答案 1 :(得分:2)

我已经基于@nephiw的答案创建了答案。 由于密钥始终是问题或答案,因此奇数始终是答案,偶数始终是问题。您可以简化为一个功能,而不是两个。

const items = [
  {
    Id: 1,
    Text: "What kind of apple is it?",
    Desc: "",
    ParentId: 0
  },
  {
    Id: 2,
    Text: "Green Apple",
    Desc: "",
    ParentId: 1
  },
  {
    Id: 3,
    Text: "Red Apple",
    Desc: "",
    ParentId: 1
  },
  {
    Id: 4,
    Text: "Purple GMO Apple",
    Desc: "",
    ParentId: 1
  },
  {
    Id: 5,
    Text: "What is the issue with the apple?",
    Desc: "",
    ParentId: 2
  },
  {
    Id: 6,
    Text: "Spoiled.",
    Desc: "",
    ParentId: 5
  },
  {
    Id: 7,
    Text: "Taste Bad.",
    Desc: "",
    ParentId: 5
  },
  {
    Id: 8,
    Text: "Too Ripe.",
    Desc: "",
    ParentId: 5
  },
  {
    Id: 9,
    Text: "Is not an apple.",
    Desc: "",
    ParentId: 5
  },
  {
    Id: 10,
    Text: "The apple was not green.",
    Desc: "",
    ParentId: 5
  }
];

const root = items.filter(item => item.ParentId === 0);
const populateChildren = (curentItem, nested) => {
  const { Id } = curentItem;
  const key = nested % 2 === 1 ? 'ChildAnswers' : 'ChildQuestions';
  items.forEach((item) => {
    if (item.ParentId === Id) {
      if (!curentItem[key]) {
        curentItem[key] = [];
      }
      curentItem[key].push(item);
      populateChildren(item, nested + 1);
    }
  });
}
root.forEach((item) => { 
  populateChildren(item, 1);
});
console.log(root);

答案 2 :(得分:2)

您可以采取一种方法,即独立于给定数据的顺序来收集零件,并通过设置问题/答案方案来构建树并映射子项。

var data = [{ Id: 1, Text: 'What kind of apple is it?', Desc: '', ParentId: 0 }, { Id: 2, Text: 'Green Apple', Desc: '', ParentId: 1 }, { Id: 3, Text: 'Red Apple', Desc: '', ParentId: 1 }, { Id: 4, Text: 'Purple GMO Apple', Desc: '', ParentId: 1 }, { Id: 5, Text: 'What is the issue with the apple?', Desc: '', ParentId: 2 }, { Id: 6, Text: 'Spoiled.', Desc: '', ParentId: 5 }, { Id: 7, Text: 'Taste Bad.', Desc: '', ParentId: 5 }, { Id: 8, Text: 'Too Ripe.', Desc: '', ParentId: 5 }, { Id: 9, Text: 'Is not an apple.', Desc: '', ParentId: 5 }, { Id: 10, Text: 'The apple was not green.', Desc: '', ParentId: 5 }],
    tree = function (data, root) {
        const
            next = { ChildAnswers: 'ChildQuestion', ChildQuestion: 'ChildAnswers' },
            toggle = type => ({ children, ...o }) =>
                Object.assign(o, children && { [type]: children.map(toggle(next[type])) }),
            t = {};

        data.forEach(o => {
            Object.assign(t[o.Id] = t[o.Id] || {}, o);
            t[o.ParentId] = t[o.ParentId] || {};
            t[o.ParentId].children = t[o.ParentId].children || [];
            t[o.ParentId].children.push(t[o.Id]);
        });
        return t[root].children.map(toggle('ChildAnswers'));
    }(data, 0);

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