在视图中将数据分组-Node.js

时间:2018-08-27 17:41:25

标签: node.js postgresql

我从postgresql DB中获取了一些数据,并希望将其显示在一个视图中,如下所示足够简单

routes.js

app.get('/fixtures', async (req, res) => {
  const fixtures = await queries.getFixtures();
  res.render('fixtures', { fixtures });
});

fixtures returns
[ { id: 27,
    home_team: 'Chelsea',
    away_team: 'Liverpool',
    league_name: 'English Premiership',
  },
  { id: 25,
    home_team: 'Man Utd',
    away_team: 'Everton',
    league_name: 'English Premiership',
  },
  { id: 30,
    home_team: 'Istanbul Basaksehir',
    away_team: 'Akhisar Belediye',
    league_name: 'Turkish Super Lig',
  }
]

getFixtures();

async function getFixtures() {
  let response;
  try {
    response = await pool.query('select * from fixtures ORDER BY league_name ASC');
  } catch (e) {
    console.error('Error Occurred', e);
  }
  return response.rows;
}

fixtures.ejs

<% fixtures.forEach((fixture) => { %>
   <p><%=fixture.league_name %></p>
   <p><%= fixture.home_team %> vs <%= fixture.away_team %> </p>
<% }) %>

因此上面的内容将输出

English Premiership
Chelsea vs Liverpool

English Premiership
Man Utd v Everton

Turkish Super Lig
Istanbul Basaksehir vs Akhisar Belediye

但是我想将我的装置按联赛分组,并且希望将视图输出显示为

English Premiership
Chelsea vs Liverpool
Man Utd v Everton

Turkish Super Lig
Istanbul Basaksehir vs Akhisar Belediye

如何实现这一目标?这是数据库查询级别的事情还是我在视图中执行的事情? (尽管我猜这可能不是保持逻辑的最佳场所)

谢谢

1 个答案:

答案 0 :(得分:1)

我不确定您使用的是什么工具/库,但是不依赖于任何库/工具,您可以使用香草JavaScript来进行操作。例如,检查以下代码:

app.get('/fixtures', async (req, res) => {

    const fixtures = await queries.getFixtures();

    const grouped = groupByLeagueName(fixtures);

    res.render('fixtures', { fixtures: grouped });
});

然后,像这样实现groupByLeagueName函数:

function groupByLeagueName(fixtures) {

    return fixtures.reduce((result, item) => {

        result[item.league_name] = result[item.league_name] || [];

        result[item.league_name].push(item);

        return result;

    }, {});
}

然后在您的视图中,您可以像这样循环它:

<% for (let leagueName in fixtures) { %>

    <p><%= leagueName %></p>

    <% fixtures[leagueName].forEach((match, key) => { %>

        <p><%= match.home_team %> vs <%= match.away_team %> </p>

    <% }) %>

<% } %>