这是我的数组,我需要按部门分组。这里的dept是一个数组,因此我需要按其dept值进行分组。
myArray = [
{name: "one", dept: ["red", "blue"]},
{name: "two", dept: ["green", "blue"]}
]
我尝试使用此代码,但无法获得所需的内容。
let deptObj = {};
_.map(myArray , el => {
const mySubArray= [];
_.filter(el.dept, (depts, i) => {
mySubArray.push(el.member);
deptObj[depts] = mySubArray;
})
}
});
我需要这样的结果,有人可以帮助我吗?
deptObj={
red:[
{name: "one", dept:["red", "blue"]}
],
blue:[
{name: "one", dept:["red", "blue"]},
{name: "two", dept:["green", "blue"]}
],
green:[
{name: "two", dept:["green", "blue"]}
]
}
答案 0 :(得分:1)
此解决方案可以满足您的需求:
limit 36
答案 1 :(得分:1)
您可以使用Array.reduce()
:
var arr = [
{name: "one", dept: ["red", "blue"]},
{name: "two", dept: ["green", "blue"]}
];
var result = arr.reduce((a,curr)=>{
curr.dept.forEach((e)=>{ (a[e] = (a[e] || [])).push(curr)});
return a;
},{});
console.log(JSON.parse(JSON.stringify(result)));
答案 2 :(得分:0)
有趣的问题。这是另一个解决方案,它是“一个衬套”,并使用 .reduce / .map / _。concat
:const arr = [{name: "one", dept: ["red", "blue"]},{name: "two", dept: ["green", "blue"]}]
var result = arr.reduce((r, {dept}, i, a) => dept.map(x => r[x] = _.concat(r[x] || [], [a[i]])) && r, {})
console.log(result)