如何使用lodash
或javascript:
[
{
"roleId": "1",
"name": "Superadmin"
"permissions": [
{
"permissionId": "1",
"action": "Remove"
}
]
},
"id": "2",
"name": "Administrator",
"permissions": [
{
"permissionId": "1",
"action": "Remove"
},
{
"permissionId": "2",
"action": "Create"
},
{
"permissionId": "3",
"action": "Read"
}
]
]
对此:
{
Superadmin: ['Remove'],
Administrator: ['Remove', 'Create', 'Read']
}
答案 0 :(得分:3)
包含Array#forEach
和Array#map
的提案。
var array = [{ "roleId": "1", "name": "Superadmin", "permissions": [{ "permissionId": "1", "action": "Remove" }] }, { "id": "2", "name": "Administrator", "permissions": [{ "permissionId": "1", "action": "Remove" }, { "permissionId": "2", "action": "Create" }, { "permissionId": "3", "action": "Read" }] }],
object = {};
array.forEach(function (a) {
object[a.name] = a.permissions.map(function (b) {
return b.action;
});
});
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
&#13;
答案 1 :(得分:2)
您可以使用reduce
&amp; map
var temp = [{
"roleId": "1",
"name": "Superadmin",
"permissions": [{
"permissionId": "1",
"action": "Remove"
}]
}, {
"id": "2",
"name": "Administrator",
"permissions": [{
"permissionId": "1",
"action": "Remove"
}, {
"permissionId": "2",
"action": "Create"
}, {
"permissionId": "3",
"action": "Read"
}]
}]
temp.reduce((result,obj)=>{
result[obj.name] = obj.permissions.map(x=>x.action)
return result;
},{});
答案 2 :(得分:2)
从评论中看到格式化和有效的json,这是你可以使用的东西。
var arr = [{
"roleId": "1",
"name": "Superadmin",
"permissions": [{
"permissionId": "1",
"action": "Remove"
}]
}, {
"id": "2",
"name": "Administrator",
"permissions": [{
"permissionId": "1",
"action": "Remove"
}, {
"permissionId": "2",
"action": "Create"
}, {
"permissionId": "3",
"action": "Read"
}]
}];
var newArray = arr.map(function(obj){
var rObj = {};
rObj[obj.name] = obj.permissions.map(function(childObj){
return childObj.action;
});
return rObj;
});
console.log(newArray);
答案 3 :(得分:2)
var json = [{
"roleId": "1",
"name": "Superadmin",
"permissions": [{
"permissionId": "1",
"action": "Remove"
}]
}, {
"roleId": "2",
"name": "Administrator",
"permissions": [{
"permissionId": "1",
"action": "Remove"
}, {
"permissionId": "2",
"action": "Create"
}, {
"permissionId": "3",
"action": "Read"
}]
}];
var roles = {};
json.forEach(function(obj) {
var actions = [];
obj.permissions.forEach(function(permission) {
actions.push(permission.action);
});
roles[obj.name] = actions;
});
console.log(roles);
这正是你想要的。只需遍历JSON对象并获取将它们存储在另一个对象(角色)中所需的属性。
输出:
{
Superadmin: ['Remove'],
Administrator: ['Remove', 'Create', 'Read']
}