大家好,请您帮我减少数组。我有两个数组,我需要在中期将其中一个分组。在这里您可以找到示例
我有对象数组
const arr = [{
mid: 888,
name: "test"
},
{
mid: 888,
name: "test1"
},
{
mid: 888,
name: "test2"
},
{
mid: 777,
name: "test10"
},
]
但是我需要中途分组并得到类似的东西
const arr = [{
mid: 888,
projects: [{
name: "test"
},
{
name: "test1"
},
{
name: "test2"
},
]
},
{
mid: 777,
projects: [{
name: "test10"
}, ]
}
]
答案 0 :(得分:1)
const arr = [{
mid: 888,
name: "test"
},
{
mid: 888,
name: "test1"
},
{
mid: 888,
name: "test2"
},
{
mid: 777,
name: "test10"
}
];
let newArray = []
arr.map(item => item.mid).filter((value, index, self)=> {
return self.indexOf(value) === index;
}).forEach((mid)=>{
newArray.push({
mid,
projects: arr.filter(item => item.mid == mid).map(item =>{ return {name: item.name}; })
})
})
console.log(newArray)
使用reduce
的其他方式:
const arr = [{
mid: 888,
name: "test"
},
{
mid: 888,
name: "test1"
},
{
mid: 888,
name: "test2"
},
{
mid: 777,
name: "test10"
}
];
newArray = arr.map(item => item.mid).filter((value, index, self)=> {
return self.indexOf(value) === index;
}).map(item=> { return {mid: item, projects: []}})
newArray = arr.reduce((res, current)=>{
let index = newArray.map(item => item.mid).indexOf(current.mid);
res[index].projects.push({name: current.name})
return res;
}, newArray)
console.log(newArray)
答案 1 :(得分:0)
这不是最快的方法,但是可以通过对代码段进行试验来帮助更好地理解reduce函数* JsFiddle
let arr = [{
mid: 888,
name: 'test'
},
{
mid: 888,
name: 'test1'
},
{
mid: 888,
name: 'test2'
},
{
mid: 777,
name: 'test10'
},
]
let reduced = arr.reduce((prev, now) => {
// first iteration, prev == []
// now == { mid: 888, name: 'test' }
let index = prev.map(e => e.mid).indexOf(now.mid);
if (~index) { // if index found
prev[index].projects.push({
name: now.name
})
} else {
prev.push({
mid: now.mid,
projects: [{
name: now.name
}]
})
}
return prev;
}, []); /* Starting from empty array */
console.log( reduced );
答案 2 :(得分:0)
您可以像这样将其分组。
var groupedData = _.mapValues(_.groupBy(arr, 'mid'),
clist => clist.map(car => _.omit(car, 'mid')));
结果将是
{888: [{
name: test
},
{
name: test1
},
{
name: test2
},
],
777: [{
name: test10
} ]}
答案 3 :(得分:0)
这是一个reduce
函数如何使用filter
和三进制大小来完成技巧:
const arr = [{mid: 888,name: "test"},
{mid: 888,name: "test1"},
{mid: 888, name: "test2"},
{mid: 777, name: "test10"}];
let newArray = arr.reduce(function (r, row) {
let dt = r.filter(x => x.mid == row.mid);
dt.length ? dt[0].projects.push(row.name): r.push({mid: row.mid, projects: [row.name]});
return r;
}, []);
console.log(newArray);