我有對象的數組,象那些的:從對象的普通數組構建數據的嵌套樹
{
"short_id": "2p45q",
"path": "/",
"name": {
"en-US": "IndustrialDesign"
}
}
...
{
"short_id": "2q56r",
"path": "/2p45q/",
"name": {
"en-US": "Automotive"
}
}
我必須遍歷數組的每個元素,並檢查path
,然後找到父元素,並將其推入該父元素的新數組屬性sub
。每個孩子可以擁有自己的sub
財產,因此是更多孩子的父母。最終的結果(在這個例子中)看起來像:
{
"short_id": "2p45q",
"path": "/",
"name": {
"en-US": "Test A"
},
"sub": [
{
"short_id": "2q56r",
"path": "/2p45q/",
"name": {
"en-US": "Test A.1"
}
}
]
}
我有(使用this jsonpath lib)工作代碼:
function(categories) {
var _categories = [];
angular.forEach(angular.copy(categories), function(_category) {
if (_category.path === "/") {
_categories.push(_category);
} else {
var _path = _category.path.split("/");
_path.pop();
var _parent = _path.pop();
jsonpath.apply(_categories, "$..[?(@.short_id=='" + _parent + "')]", function(obj) {
if(!obj.hasOwnProperty("sub")) {
obj.sub = [];
}
obj.sub.push(_category);
return obj;
});
}
});
return _categories;
}
但表現實在是太差了,主要是因爲我查詢整個數組用於每次迭代。
我的問題是如何優化我的代碼?
注:
- 每個
short_id
恰好長5個字符。 - 在
short_id
每個字符都可以是[0-9a-z]
path
是保證開頭和/
我不知道我理解它是如何工作的。 'short_id'是唯一的,所以'store'永遠不會有'key'('path + short_id')。 – alexandernst
假設我們有一個父路徑爲'/'和id'2p45q',我們創建一個鍵爲'/ 2p45q /'並用它存儲在散列映射中,所以當一個子路徑爲'/ 2p45q /'時,我們知道'store ['/ 2p45q /']'是它的父親。 – fuyushimoya
哦,好吧,現在有道理。謝謝! – alexandernst