【问题标题】:How do I combine a list of objects where each object has duplicate category and unique article?如何组合每个对象具有重复类别和唯一文章的对象列表?
【发布时间】:2019-03-11 05:07:36
【问题描述】:

我想合并此数据集中的所有 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.id 匹配,则在相同的category 下方。像这样:

[
  {
    category: {
      id: 1,
    },
    articles: [
      {
        title: 'aaa',
      },
      {
        title: 'bbb',
      },
    ]
  },
  {
    category: {
      id: 2,
    },
    articles: [
      {
        title: 'ccc',
      }
    ],
  },
  {
    category: {
      id: 3,
    },
    articles: [
      {
        title: 'ddd',
      },
      {
        title: 'eee'
      }
    ]
  },
]

有什么想法吗?很高兴使用 Lodash 的东西。谢谢!

【问题讨论】:

    标签: javascript arrays object lodash javascript-objects


    【解决方案1】:

    您可以使用reduce 函数。在reduce回调函数内部使用findIndex检查累加器数组是否有一个对象id与当前迭代对象的id相同。如果相同,则更新文章数组,否则使用所需键创建一个新对象并将其推送到累加器数组

    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)

    【讨论】:

    • 太棒了。非常感谢@brk!
    猜你喜欢
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 2017-02-09
    • 2023-03-07
    • 2017-02-21
    • 1970-01-01
    相关资源
    最近更新 更多