親IDに基づいて階層カテゴリオブジェクトをソートし、次にそのレベルに基づいて親と一緒に表示しようとしています。
これが私のオブジェクトの外観です
[{category_id: "168"
category_level: "1"
category_name: "Home"
parent_id: "1"},
{category_id: "166"
category_level: "1"
category_name: "Living"
parent_id: "1"},
{category_id: "171"
category_level: "2"
category_name: "Chairs"
parent_id: "168"},
{category_id: "172"
category_level: "3"
category_name: "Single Sofa"
parent_id: "170"},
{category_id: "169"
category_level: "1"
category_name: "Patio"
parent_id: "1"},
{category_id: "170"
category_level: "2"
category_name: "Sofa"
parent_id: "166"},
]
** JSON 期待される出力**
[{category_id: "168"
category_level: "1"
category_name: "Home"
parent_id: "1"},
{category_id: "169"
category_level: "1"
category_name: "Patio"
parent_id: "1"},
{category_id: "166"
category_level: "1"
category_name: "Living"
parent_id: "1"},
{category_id: "170"
category_level: "2"
category_name: "Sofa"
parent_id: "166"},
{category_id: "172"
category_level: "3"
category_name: "Single Sofa"
parent_id: "170"},
{category_id: "171"
category_level: "2"
category_name: "Chairs"
parent_id: "168"}]
出力は次のようになります
Home
Patio
Living
Living >> Sofa
Living >> Sofa >> Single Sofa
Living >> Chairs
ここで ag-grid を使用し、lodash.js で解決しようとしました。列定義でセルをレンダリングするために使用したコードは次のとおりです。
var columnDefs = [
{headerName: "", field: "icon", width:52},
{headerName: "Categories",field:"category_name", width:1000, cellRenderer:function(params){
function getParentIndex(pid)
{
var index = $scope.categories.map(function(el){
return el.category_id;
}).indexOf(pid);
return index
}
var val="", parentIndex = getParentIndex(params.data.parent_id);
if(parentIndex > -1)
{
val = $scope.categories[parentIndex].category_name + " >> " +params.data.category_name;
var grandParentIndex = getParentIndex($scope.categories[parentIndex].parent_id);
if(grandParentIndex > -1)
{
val = $scope.categories[grandParentIndex].category_name + " >> " + val;
}
}
else {
val = params.data.category_name;
}
return val;
}},
{headerName: "", field: "options", width:87, suppressMenu: true, onCellClicked(params){
$scope.modifyOptions(params.data);
}, template:"<a class='btn' href='javascript:void(0)'>options</a>"
}
];
上記のコードは文字列をうまく連結しますが、出力に示されているようにソートする必要があります。これは私のlodash.jsコードです。短いですが、単一のカテゴリのみです。
var parentId = 1;
var sortedList = [];
var byParentsIdsList = _.groupBy(scope.categories, "parent_id"); // Create a new array with objects indexed by parentId
while (byParentsIdsList[parentId]) {
sortedList.push(byParentsIdsList[parentId][0]);
parentId = byParentsIdsList[parentId][0].category_id;
}
scope.categories = sortedList;