本文介绍了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);
这篇关于JavaScript按值对对象进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!