JavaScript按值对对象进行分组
首先,我需要根据策略属性值对对象数组进行分组。然后,我需要对操作和公司字段进行分组。我尝试使用lodash,但无法访问嵌套数组。
来自此=>;
[
{
"action": "VIEW",
"policy": "FORM"
},
{
"action": "CREATE",
"policy": "USER"
},
{
"action": "VIEW",
"policy": "USER"
},
{
"company": "Microsoft",
"policy": "FORM"
},
{
"company": "Facebook",
"policy": "USER"
},
{
"company": "Twitter",
"policy": "USER"
}
]
至此=>;
{
"FORM": {
"action": ["VIEW"],
"company": ["Microsoft"]
},
"USER": {
"action": ["CREATE", "VIEW"],
"company": ["Facebook", "Twitter"]
}
}
非常感谢
解决方案
可以使用简单的for...of
循环和一些destructuring
:
const data = [ { action: 'VIEW', policy: 'FORM', }, { action: 'CREATE', policy: 'USER', }, { action: 'VIEW', policy: 'USER', }, { company: 'Microsoft', policy: 'FORM', }, { company: 'Facebook', policy: 'USER', }, { company: 'Twitter', policy: 'USER', }, ];
let result = {};
for (const { action, policy, company } of data) {
result[policy] = result[policy] ?? { action: [], company: [] };
if (action) result[policy].action.push(action);
if (company) result[policy].company.push(company);
}
console.log(result);
您也可以使用array#reduce
而不是for循环:
const data = [ { action: 'VIEW', policy: 'FORM' }, { action: 'CREATE', policy: 'USER' }, { action: 'VIEW', policy: 'USER' }, { company: 'Microsoft', policy: 'FORM' }, { company: 'Facebook', policy: 'USER' }, { company: 'Twitter', policy: 'USER' }, ];
const result = data.reduce((result, { action, company, policy }) => {
result[policy] = result[policy] ?? { action: [], company: [] };
action && result[policy].action.push(action);
company && result[policy].company.push(company);
return result;
}, {});
console.log(result);
相关文章