我有一个简单的对象
var xobj = [
{ role:"Organize Admin", role_id:"id1", permission_name:"View All Users",active: "true" },
{ role:"Organize Admin", role_id:"id1", permission_name:"Create users", active: "true" },
{ role:"Organize Admin", role_id:"id1", permission_name:"Edit users", active: "true" },
{ role:"System Admin", role_id:"id2", permission_name:"Edit users", active: "true" },
{ role:"System Admin", role_id:"id2", permission_name:"Edit users", active: "true" },
];
我正在努力根据role_id重组对象,同时为每个role_id分组权限
实现这一目标的有效方法是什么?
答案 0 :(得分:1)
使用.reduce
对角色对象进行分组,并使用.find
在内部查找累加器数组中匹配的id
对象(如果存在):
const input = [
{ role:"Organize Admin", role_id:"id1", permission_name:"View All Users",active: "true" },
{ role:"Organize Admin", role_id:"id1", permission_name:"Create users", active: "true" },
{ role:"Organize Admin", role_id:"id1", permission_name:"Edit users", active: "true" },
{ role:"System Admin", role_id:"id2", permission_name:"Edit users", active: "true" },
{ role:"System Admin", role_id:"id2", permission_name:"Edit users", active: "true" },
];
const roles = input.reduce((a, { role_id, permission_name: name, active }) => {
const foundRole = a.find(({ id }) => id === role_id);
if (foundRole) foundRole.permissions.push({ name, active });
else a.push({ id: role_id, permissions: [{ name, active }] });
return a;
}, []);
console.log(roles);
答案 1 :(得分:0)
另一种方法是使用对象并将内容累积到其属性中
var xobj = [
{ role:"Organize Admin", role_id:"id1", permission_name:"View All Users",active: "true" },
{ role:"Organize Admin", role_id:"id1", permission_name:"Create users", active: "true" },
{ role:"Organize Admin", role_id:"id1", permission_name:"Edit users", active: "true" },
{ role:"System Admin", role_id:"id2", permission_name:"Edit users", active: "true" },
{ role:"System Admin", role_id:"id2", permission_name:"Edit users", active: "true" },
];
var groups = {};
xobj.forEach(obj => {
if(!groups.hasOwnProperty(obj.role_id)){
groups[obj.role_id] = [];
}
groups[obj.role_id].push(obj);
})
console.log(groups)

答案 2 :(得分:0)
这是另一种解决方案:
搜索用于分组的唯一键。如果不存在,则添加它并使用当前值为其分配一个数组。否则,将当前项目附加到现有密钥上。
var xobj = [{
role: "Organize Admin",
role_id: "id1",
permission_name: "View All Users",
active: "true"
},
{
role: "Organize Admin",
role_id: "id1",
permission_name: "Create users",
active: "true"
},
{
role: "Organize Admin",
role_id: "id1",
permission_name: "Edit users",
active: "true"
},
{
role: "System Admin",
role_id: "id2",
permission_name: "Edit users",
active: "true"
},
{
role: "System Admin",
role_id: "id2",
permission_name: "Edit users",
active: "true"
},
];
const groupedData = xobj.reduce((acc, x) => {
const index = acc.findIndex(y => Object.keys(y)[0] === x.role_id)
if (index < 0) {
acc.push({
[x.role_id]: [x]
});
return acc;
}
acc[index] = {
...acc[index],
[x.role_id]: [...acc[index][x.role_id], x]
}
return acc;
}, [])
console.log(groupedData);
还有一个列表/数组时,请为您的变量命名,以表明它确实是列表/数组,而不是您的情况下的 xobj 。