首页 > 解决方案 > JS中的对象数组分组问题

问题描述

我有这样的对象数组:

[{id: 1, name: 'Apple', category: 'Fruit'}
{id: 2, name: 'Melon', category: 'Fruit'}
{id: 3, name: 'iPhone', category: 'Phone'}
{id: 4, name: 'Samsung Galaxy Note 8', category: 'Phone'}
{id: 5, name: 'Playstation 5', category: 'Entertainment'}]

我想要实现的是按类别组合产品名称并将它们显示为:

Fruit
  Apple
  Melon
Phone
  iPhone
  Samsung Galaxy Note 8
Entertainment
  Playstation 5

所以,我试图实现的是

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

const products = [{id: 1, name: 'Apple', category: 'Fruit'}
    {id: 2, name: 'Melon', category: 'Fruit'}
    {id: 3, name: 'iPhone', category: 'Phone'}
    {id: 4, name: 'Samsung Galaxy Note 8', category: 'Phone'}
    {id: 5, name: 'Playstation 5', category: 'Entertainment'}]

console.log(groupBy([products], 'category'));

标签: javascriptreactjs

解决方案


生成 HTML 代码

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

const products = [{id: 1, name: 'Apple', category: 'Fruit'},
{id: 2, name: 'Melon', category: 'Fruit'},
{id: 3, name: 'iPhone', category: 'Phone'},
{id: 4, name: 'Samsung Galaxy Note 8', category: 'Phone'},
{id: 5, name: 'Playstation 5', category: 'Entertainment'}];

const groups = groupBy(products, 'category');
const html = Object.keys(groups).reduce((code, cat) => {
  const inner = groups[cat].reduce((i, product) => {
    return i + `<p>${product.name}</p>`;
  }, '');
  return code + `<div><h2>${cat}</h2>${inner}</div>`;
}, '');

document.getElementById('container').innerHTML = html;
p { margin-left: 20px; }
<div id="container"></div>


推荐阅读