按属性组合对象数组
您好,我试图结合一个对象数组,并需要最终的结果是一个对象的数组,其中一个attr是唯一的,另一个是具有所有值的数组从原始的按属性组合对象数组
阵列第二ATTR我:
let arr = [ {
name: 'cdd_register',
levels: 'read'
}, {
name: 'cdd_register',
levels: 'write'
}, {
name: 'annual_reports',
levels: 'write'
}
];
而且我希望得到的结果是:
let result = [ {
name: 'cdd_register',
levels: ['read', 'write']
}, {
name: 'annual_reports',
levels: 'write'
}
];
我从后端
data: [{ id:1
label: "Administrator"
name: "admin"
permissions:{
data: [{
id: 4,
name: "cdd_register.read",
label: "Read access on CDD Register module"
}, {
id: 6,
name: "cdd_register.write",
label: "Write access on CDD Register module"
}, {
id: 7,
name: "annual_reports.write",
label: "Write access on Annual Reports module"
}]
}
}]
这种答复,这
getModules(roles) { let modules = [];
_.forEach(roles, role => {
_.forEach(role.permissions.data, permission => {
modules.push(permission);
})
});
return _.uniqBy(modules, 'id').map(module => {
let moduleArray = module.name.split('.');
return {
name: moduleArray[0],
levels: moduleArray[1]
}
});
}
}
后,我有结果,因为它是现在,但无法弄清楚做的最好的方式(干净)。
谢谢。
回答:
这可以用许多不同的方法完成。一种可能的方法可以使用一些魔法的功能
let arr = [{ name: 'cdd_register',
levels: 'read'
}, {
name: 'cdd_register',
levels: 'write'
}, {
name: 'annual_reports',
levels: 'write'
}];
let result = arr.reduce((acc, x) => {
const found = acc.find(y => (x.name == y.name));
if (!found) {
acc.push({
name: x.name,
levels: arr
.filter(y => (x.name == y.name))
.map(z => (z.levels))
});
}
return acc;
}, [])
console.log(result)
以上是 按属性组合对象数组 的全部内容, 来源链接: utcz.com/qa/259007.html