如何使用 lodash 从对象数组创建具有名称和频率计数的对象

How to create an object with the name and frequency count from an object array with lodash

我有一个这样的数组:

const blogs = [
  {
    _id: "5a422a851b54a676234d17f7",
    title: "React patterns",
    author: "Michael Chan",
    url: "https://reactpatterns.com/",
    likes: 7,
    __v: 0
  },
  {
    _id: "5a422ba71b54a676234d17fb",
    title: "TDD harms architecture",
    author: "Robert C. Martin",
    url: "http://blog.cleancoder.com/uncle-bob/2017/03/03/TDD-Harms-Architecture.html",
    likes: 0,
    __v: 0
  },
  {
    _id: "5a422bc61b54a676234d17fc",
    title: "Type wars",
    author: "Robert C. Martin",
    url: "http://blog.cleancoder.com/uncle-bob/2016/05/01/TypeWars.html",
    likes: 2,
    __v: 0
  }  
]

我想要至少一个这样的对象:

{
    "name":"Robert C. Martin",
    "blogs": 2,
}

我尝试使用 lodash,但不明白如何计算一位作者的博客数量。

_.maxBy(blogs, 'author') //gives me the author with the maximum of blogs
_.groupBy(blogs, 'author') // group all blogs in an array under the author name
// _.countBy(blogs,'entries') //that doesn't work

如果您不想使用 lodash,使用普通的 JavaScript(参见 Array.prototype.reduce)就足够简单了,例如:

const blogs = [{
    _id: "5a422a851b54a676234d17f7",
    title: "React patterns",
    author: "Michael Chan",
    url: "https://reactpatterns.com/",
    likes: 7,
    __v: 0
  },
  {
    _id: "5a422ba71b54a676234d17fb",
    title: "TDD harms architecture",
    author: "Robert C. Martin",
    url: "http://blog.cleancoder.com/uncle-bob/2017/03/03/TDD-Harms-Architecture.html",
    likes: 0,
    __v: 0
  },
  {
    _id: "5a422bc61b54a676234d17fc",
    title: "Type wars",
    author: "Robert C. Martin",
    url: "http://blog.cleancoder.com/uncle-bob/2016/05/01/TypeWars.html",
    likes: 2,
    __v: 0
  }
];

const blogAuthorCounter = blogs.reduce((obj, blog) => {
  obj[blog.author] = obj[blog.author] ? obj[blog.author] + 1 : 1;

  return obj;
}, {});

Object.entries(blogAuthorCounter).forEach(entry => {
  const [author, count] = entry;

  console.log(`${author} = ${count}`);
});