我想在这个数据集中组合所有article
对象:
const data = [
{
category: {
id: 1,
},
article: {
title: 'aaa',
},
},
{
category: {
id: 1,
},
article: {
title: 'bbb',
},
},
{
category: {
id: 2,
},
article: {
title: 'ccc',
},
},
{
category: {
id: 3,
},
article: {
title: 'ddd',
},
},
{
category: {
id: 3,
},
article: {
title: 'eee',
},
},
]
如果category
匹配,在相同的category.id
下面。像这样:
[
{
category: {
id: 1,
},
articles: [
{
title: 'aaa',
},
{
title: 'bbb',
},
]
},
{
category: {
id: 2,
},
articles: [
{
title: 'ccc',
}
],
},
{
category: {
id: 3,
},
articles: [
{
title: 'ddd',
},
{
title: 'eee'
}
]
},
]
有任何想法吗?很高兴使用Lodash的东西。谢谢!
你可以使用reduce
功能。在reduce reduce回调函数中使用findIndex
检查累加器数组是否有一个id
对象与迭代时当前对象的id相同。如果它相同则更新articles数组,否则使用required键创建一个新对象并将其推送到累加器数组
const data = [{
category: {
id: 1,
},
article: {
title: 'aaa',
},
},
{
category: {
id: 1,
},
article: {
title: 'bbb',
},
},
{
category: {
id: 2,
},
article: {
title: 'ccc',
},
},
{
category: {
id: 3,
},
article: {
title: 'ddd',
},
},
{
category: {
id: 3,
},
article: {
title: 'eee',
},
}
]
let newData = data.reduce(function(acc, curr) {
let findIdIndex = acc.findIndex(function(item) {
return item.category.id === curr.category.id
});
if (findIdIndex === -1) {
acc.push({
category: {
id: curr['category']['id']
},
articles: [{
title: curr.article.title
}]
})
} else {
acc[findIdIndex].articles.push({
title: curr.article.title
})
}
return acc;
}, []);
console.log(newData)