假设我有一系列文章,每篇文章可能有也可能没有超过 1 个图像对象,现在由于 mysql 无法将对象分组在一起,所以你必须自己做。所以结果是你得到near重复的文章对象...唯一的区别是图像对象。By near重复我的意思是返回结果的唯一区别是图像对象。
我正在尝试找到一种方法来循环articles
数组并消除重复的对象并创建一个images
数组将保存每个article
图像对象。
例如,给出以下一系列文章:
{ articles: [
{article: {articleId: 10, articleText: 'blah'}, image: {articleId: 10, imageUrl: 'http://differentUrlTooBelow'} },
{article: {articleId: 10, articleText: 'blah'}, image: {articleId: 10, imageUrl: 'http://AnotherUrlDifferentToAbove'} },
{article: {articleId: 11, articleText: 'ajsdnfa'}, image: {articleId: 11, imageUrl: 'http://DifferentUrlTooBelow'} },
{article: {articleId: 11, articleText: 'asfdjnasjdf'}, image: {articleId: 11, imageUrl: 'http://AnotherUrlDifferentToAbove'} },
]}
我们可以使用lodash的reduce函数,但它似乎只返回最后一个article (articleId: 11)
...它似乎也没有找到所有图像。它只会在每篇文章中创建一个图像数组。注意res是数组article对象(如上所示)
var z = _.reduce(res, function(result, value, key) {
if (key == 0) return;
if(value.article['articleId'] == res[key-1].article['articleId']) {
result = value;
result.images = [];
result.images.push(result.image);
}
return result;
}, {});
最终结果看起来像这样:
{ articles: [
{article: {articleId: 10, articleText: 'blah'},
images: [
{articleId: 10, imageUrl: 'http://differentUrlTooBelow'},
{articleId: 10, imageUrl: 'http://AnotherUrlDifferentToAbove'}
]},
{article: {articleId: 11, articleText: 'blah'},
images: [
{articleId: 11, imageUrl: 'http://differentUrlTooBelow'},
{articleId: 11, imageUrl: 'http://AnotherUrlDifferentToAbove'}
]},
]}