0
我想將一個描述爲具有座標和大小的項目數組的扁平網格轉換爲一個嵌套的網格,並將其組織成行和列。如何將平面網格轉換爲嵌套網格?
編輯:在這個問題的第一個版本中,我用「矩陣」這個術語來談論處於扁平狀態的網格。這可能是令人困惑的,這個問題的真正目的是從一個一個走向另一個。無論如何,人們可以很容易地將一個矩陣轉換成一個平坦的陣列,比如我用它來將它轉換成一棵樹。
有一個平坦的網格如:
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
}
]
似乎樣品基質並不匹配輸出。列和行如何組織? – RobG
哦,你是對的!我編輯了結果數組。這裏的邏輯是矩陣應該被轉換成列的行。每個包含多行的列應該分割成若干行,等等...... – Jide
清晰如泥。 ;-)如果你提供一個樣本矩陣,並從樣本矩陣中抽出*,你可能會得到一個答案。 – RobG