基于虚线键父值从平面数组创建关联数组

时间:2017-11-29 07:16:03

标签: javascript arrays sorting

我在从平面数组创建格式化数组时遇到问题,父数值采用点分隔格式。喜欢..

  • 管理员是用户的父级:用户父级admin
  • 用户是...的父级 test:测试父级是admin.user

我想要数据的格式是。

admin: {
    data: {...admin obj..},
    children: [{
        user: {
                data: {...user obj...},
                children: [..and so on]
            }
    }]
}
  

提供的数据格式为

[{
    "name": "admin",
    "display_name": "Menu",
    "type": 1,
    "applies_to": null,
    "perm_parent_id": null,
    "description": "Can see the admin menu item"
}, {
    "name": "admin.users",
    "display_name": "Menu",
    "type": 1,
    "applies_to": null,
    "perm_parent_id": "admin",
    "description": null
}, {
    "name": "admin.users.edit",
    "display_name": "Edit",
    "type": 1,
    "applies_to": null,
    "perm_parent_id": "admin.users",
    "description": null
}, {
    "name": "admin.users.view",
    "display_name": "View",
    "type": 1,
    "applies_to": null,
    "perm_parent_id": "admin.users",
    "description": null
}, {
    "name": "admin.groups",
    "display_name": "Groups & Permissions",
    "type": 1,
    "applies_to": null,
    "perm_parent_id": "admin",
    "description": null
}]
  

到目前为止我所做的是:

 var groups = myjson.reduce(function(arr, a) {
var key = a['perm_parent_id'];
var level = keys.length;
if (a['perm_parent_id'] === null) {
arr[key] = arr[key] || {}
arr[key]["data"] = a || {};
arr[key]["children"] = [];
} else {
arr[key] = arr[key] || {}
arr[key] = arr[key] || {};
arr[key]["children"] = arr[key]["children"] || [];
arr[key]["children"].push(a);
}
return arr;
}, {})

0 个答案:

没有答案