如何合并一组对象?

时间:2016-04-29 03:20:38

标签: javascript arrays lodash

假设我有一系列文章,每篇文章可能有也可能没有超过1个图像对象,现在因为mysql不能将对象组合在一起,所以你必须自己做。因此,结果是你得到接近重复的文章对象......其中唯一的区别是图像对象。 靠近重复,我的意思是返回结果的唯一区别是图像对象。

我试图找到一种方法来遍历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 文章对象的数组(如上所示)

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'} 
   ]},
]}

1 个答案:

答案 0 :(得分:2)

您可以使用_.groupBy()匹配article.articleId,然后_.map()使用第一项关联每篇文章,然后通过获取所有{images属性来设置image属性1}}项目通过_.map()

var data = { 
  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' } 
   }
  ]
};

var result = {
  articles: _(data.articles)
    .groupBy('article.articleId')
    .map(function(items) {
      return _(items[0])
        .omit('image')
        .set('images', _.map(items, 'image'))
        .value();
    })
    .value()
};

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"></script>