anonymous No title
No License JavaScript
2021年05月07日
Copy Clone
const input = [
  { level: 1, text: "1章 JavaScriptの第一歩" },
  { level: 1, text: "2章 データ型と変数" },
  { level: 2, text: "2.1 変数の識別" },
  { level: 2, text: "2.2 スコープ" },
  { level: 1, text: "第3章 演算子と文" },
  { level: 2, text: "3.1 文の形式" },
  { level: 2, text: "3.2 単純文" },
  { level: 3, text: "3.2.1 代入文" },
  { level: 3, text: "3.2.2 演算文" },
];

function treefy(input) {
  const output = [];
  const containers = [output];
  let level = 1;

  for (let i = 0; i < input.length; i++) {
    const item = input[i];

    if (item.level > level) {
      input[i-1].children = [item];
      containers.push(input[i-1].children);
    } else if (item.level < level) {
      containers.pop();
    }
    
    containers[containers.length-1].push(item);
    level = item.level;
  }

  return output;
}

console.log(
  JSON.stringify(treefy(input), null, '\t')
);
const input = [
  { level: 1, text: "1章 JavaScriptの第一歩" },
  { level: 1, text: "2章 データ型と変数" },
  { level: 2, text: "2.1 変数の識別" },
  { level: 2, text: "2.2 スコープ" },
  { level: 1, text: "第3章 演算子と文" },
  { level: 2, text: "3.1 文の形式" },
  { level: 2, text: "3.2 単純文" },
  { level: 3, text: "3.2.1 代入文" },
  { level: 3, text: "3.2.2 演算文" },
];

function treefy(input) {
  const output = [];
  const containers = [output];
  let level = 1;

  for (let i = 0; i < input.length; i++) {
    const item = input[i];

    if (item.level > level) {
      input[i-1].children = [item];
      containers.push(input[i-1].children);
    } else if (item.level < level) {
      containers.pop();
    }
    
    containers[containers.length-1].push(item);
    level = item.level;
  }

  return output;
}

console.log(
  JSON.stringify(treefy(input), null, '\t')
);
No one still commented. Please first comment.
Output