我想将一个描述为具有坐标和大小的项目数组的平面网格转换为一个嵌套的网格,其中包含组织成行和列的子项。
编辑:在这个问题的第一个版本中,我使用术语“矩阵”来讨论处于扁平状态的网格。这可能令人困惑,这个问题的真正目的是从平面到树。无论如何,人们可以轻松地将矩阵转换为平面数组,例如我用来将其转换为树的数组。具有平面网格,例如:
var grid = [
{x:0,y:1,w:1,h:3,id:'f'},
{x:0,y:0,w:9,h:1,id:'e'},
{x:1,y:1,w:4,h:2,id:'a'},
{x:5,y:1,w:2,h:1,id:'b'},
{x:5,y:2,w:2,h:1,id:'c'},
{x:5,y:3,w:2,h:1,id:'h'},
{x:1,y:3,w:4,h:1,id:'g'},
{x:7,y:1,w:2,h:1,id:'i'},
{x:7,y:2,w:2,h:1,id:'j'},
{x:7,y:3,w:2,h:1,id:'k'},
];
结果将是:
var grid = [
{
"w": 9,
"h": 4,
"children": [
{
"x": 0,
"y": 0,
"w": 9,
"h": 1,
"id": "e"
},
{
"w": 9,
"h": 3,
"children": [
{
"w": 8,
"h": 3,
"children": [
{
"w": 8,
"h": 1,
"children": [
{
"x": 7,
"y": 3,
"w": 2,
"h": 1,
"id": "k"
},
{
"x": 1,
"y": 3,
"w": 4,
"h": 1,
"id": "g"
},
{
"x": 5,
"y": 3,
"w": 2,
"h": 1,
"id": "h"
}
],
"x": 1,
"y": 3
},
{
"w": 8,
"h": 2,
"children": [
{
"w": 4,
"h": 2,
"children": [
{
"w": 4,
"h": 1,
"children": [
{
"x": 7,
"y": 2,
"w": 2,
"h": 1,
"id": "j"
},
{
"x": 5,
"y": 2,
"w": 2,
"h": 1,
"id": "c"
}
],
"x": 5,
"y": 2
},
{
"w": 4,
"h": 1,
"children": [
{
"x": 7,
"y": 1,
"w": 2,
"h": 1,
"id": "i"
},
{
"x": 5,
"y": 1,
"w": 2,
"h": 1,
"id": "b"
}
],
"x": 5,
"y": 1
}
],
"x": 5,
"y": 1
},
{
"x": 1,
"y": 1,
"w": 4,
"h": 2,
"id": "a"
}
],
"x": 1,
"y": 1
}
],
"x": 1,
"y": 1
},
{
"x": 0,
"y": 1,
"w": 1,
"h": 3,
"id": "f"
}
],
"x": 0,
"y": 1
}
],
"x": 0,
"y": 0
}
]
答案 0 :(得分:0)
我决定去尝试自己解决这个问题。
我承认问题制定得很糟糕,所以我对其进行了编辑以使其更准确。
要将平面网格缩小为嵌套网格,需要的步骤为:
我用我的模块制作了一个github仓库:https://github.com/jide/GridPack