javascript - 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'));
解决方案
生成 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>
推荐阅读
- sap - 钻取父子业务对象
- reactjs - 在 React Native 中查看 AsyncStorage 的工具
- react-native - 无法读取未定义的属性“导航”-React Native
- angular - 导航到页面/组件并在 Ionic4 中设置为 Root
- javascript - React Native:TypeError:babelHelpers.typeof 不是函数
- lightgbm - LightGBM 训练数据的洗牌
- javascript - 如何在 Swift 中从 npm 运行 Node JS 代码
- cakephp - cakephp 3.6 发布请求中的 CSRF 令牌不匹配
- redux - jest.mock 工厂没有被使用
- arrays - PHP preg_grep 多文件