js - 如何将表数据转换为树(JSON)

时间:2018-05-25 12:14:21

标签: javascript arrays json tree javascript-objects

我从一个看起来像这样的表(非常简化)中获取JSON数据:

table data

我得到的JSON格式如下:

const myObjOriginal = {
  "rows": [{
    "name": "row 1",
    "cells": [{
      "name": "level 1",
      "id": 1
    }, {
      "name": "first level 2",
      "id": 2
    }, {
      "name": "endpoint 1",
      "id": 4
    }]
  }, {
    "name": "row 2",
    "cells": [{
      "name": "level 1",
      "id": 1
    }, {
      "name": "first level 2",
      "id": 2
    }, {
      "name": "endpoint 2",
      "id": 5
    }]
  }, {
    "name": "row 3",
    "cells": [{
      "name": "level 1",
      "id": 1
    }, {
      "name": "second level 2",
      "id": 3
    }, {
      "name": "endpoint 3",
      "id": 6
    }]
  }]
};

我需要做的就是把它变成树而不是表,输出看起来像这样:

const goalObject = [{
  "name": "level 1",
  "id": 2,
  "children": [{
    "name": "first level 2",
    "id": 2,
    "children": [{
      "name": "endpoint 1",
      "id": 4
    }, {
      "name": "endpoint 2",
      "id": 5
    }]
  }, {
    "name": "second level 2",
    "id": 3,
    "children": [{
      "name": "endpoint 3",
      "id": 6
    }]
  }]
}];

我尝试了各种各样的事情,包括map,reduce,filter,for循环和forEach,但都无济于事。

我意识到我需要以某种方式制作一个递归函数,但我还没有这样做。

这是我尝试过的一件事的例子,但我知道这是完全错误的......

function getChildrenOfCurrentItem(rowIndex = 0, cellIndex = 0) {
  let current = {};
  let myObj = {};

  for(let i = 0; i < myCopy.rows.length; i++){
    next = myCopy.rows[i].cells[cellIndex];
    const cells = myCopy.rows[i].cells;
    const isSame = compareObjects(current, next);

    if(!isSame){
      current = next;
      myObj.item = current;
      //cellIndex++;

      for(let j = 0; j < cells.length; j++){
        let cell = cells[j];
        console.log('cell', cell);
      }
    }

    console.log('myObj', myObj);

    //cellIndex++;
    if(cellIndex < max) {
        getChildrenOfCurrentItem(rowIndex, cellIndex);
    }
    rowIndex++;
  }
  return myObj;
}

1 个答案:

答案 0 :(得分:1)

您可以通过查找具有相同id的组来使用迭代方法。

&#13;
&#13;
var data = { rows: [{ name: "row 1", cells: [{ name: "level 1", id: 1 }, { name: "first level 2", id: 2 }, { name: "endpoint 1", id: 4 }] }, { name: "row 2", cells: [{ name: "level 1", id: 1 }, { name: "first level 2", id: 2 }, { name: "endpoint 2", id: 5 }] }, { name: "row 3", cells: [{ name: "level 1", id: 1 }, { name: "second level 2", id: 3 }, { name: "endpoint 3", id: 6 }] }] },
    result = [];

data.rows.forEach(({ cells }) => {
    cells.reduce((level, { name, id }) => {
        var temp = (level.children = level.children || []).find(o => o.id === id);
        if (!temp) {
            temp = { name, id };
            level.children.push(temp);
        }
        return temp;
    }, { children: result });
});

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