Get return function to display the categorized results on the web page

蹲街弑〆低调 提交于 2020-04-18 05:34:36

问题


I have the following Alignments.js react component using the new useState and useEffect React hooks, which works great by the way. It displays a list of alignments:

import React, {useState, useEffect} from 'react';
import './App.css';
import {Link} from 'react-router-dom';

function Alignments() {
  useEffect(() => {
    fetchItems();
  },[]);

  const [items, setItems] = useState([]);

  const fetchItems = async () => {
    const data = await fetch('http://localhost:3001/alignments');
    const items = await data.json();
    setItems(items);
    console.log(items);
  };

  return (
    <div>
      {items.map(item => (
        <ul align="left" key={item.id}>
          <h2><Link to={`/alignments/${item.alignment}`}> {item.alignment}</Link></h2>
        </ul>
      ))}
    </div>
  );
}

export default Alignments;

console.log(items)

(30) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {id: 1, aligngrp1: "I124", aligngrp2: "I124", alignment: "I124", length: 9699.999985122007, …}
1: {id: 2, aligngrp1: "I124", aligngrp2: "Cross_Streets", alignment: "12th", length: 1535.818272652023, …}
2: {id: 3, aligngrp1: "I124", aligngrp2: "Cross_Streets", alignment: "13th", length: 391.437434891255, …}
3: {id: 4, aligngrp1: "I124", aligngrp2: "Cross_Streets", alignment: "4th", length: 1032.43200821333, …}
4: {id: 5, aligngrp1: "I124", aligngrp2: "Cross_Streets", alignment: "6th", length: 999.9999994234385, …}
27: {id: 28, aligngrp1: "I124", aligngrp2: "Ramps", alignment: "Ramp_O", length: 927.6421496634126, …}
28: {id: 29, aligngrp1: "I124", aligngrp2: "Ramps", alignment: "Ramp_P", length: 1418.010004687435, …}
29: {id: 30, aligngrp1: "I124", aligngrp2: "Ramps", alignment: "Ramp_R", length: 444.908879095785, …}

Okay, so now that I've fetched these alignments from my database, and they're sitting in this items array, I want to put them in categories based on a column in the table called 'aligngrp2'. Where do I add the following code so that it runs after the fetch has completed?

    const cats = items.reduce((catsSoFar, { aligngrp2, alignment }) => {
      if (!catsSoFar[aligngrp2]) catsSoFar[aligngrp2] = [];
      catsSoFar[aligngrp2].push(alignment);
    return catsSoFar;
    }, {});
    console.log(cats);
  };

or even better,

const cats = _.groupBy(items, 'aligngrp2');

I don't believe I can just add this arbitrarily to the Alignments component (which is what I did just to see a console.log of it). It shows 3 arrays, one for each aligngrp2, just the way I want it to be displayed on the web page:

{I124: Array(1), Cross_Streets: Array(12), Ramps: Array(17)}
I124: Array(1)
0: "I124"
length: 1
__proto__: Array(0)
Cross_Streets: Array(12)
0: "12th"
1: "13th"
2: "4th"
3: "6th"
length: 12
__proto__: Array(0)
Ramps: Array(17)
14: "Ramp_O"
15: "Ramp_P"
16: "Ramp_R"
length: 17
__proto__: Array(0)

Now to modify the return function in Alignments.js to display the alignments grouped by aligngrp2. If I change items.map to cats.map, it gives an error that cats.map is not a function. I tried different code to try to display this but to no avail. Do I unset items and then somehow re-add the newly grouped items? Can't figure out how to get the return function to display the new grouped list of alignments.


回答1:


you can use this Function:

 const groupBy = (items, key) =>
    items.reduce(
      (result, item) => ({
        ...result,
        [item[key]]: [...(result[item[key]] || []), item],
      }),
      {},
    )

then you can get the result :groupedData = groupBy(items, 'aligngrp2')




回答2:


You could use Lodash,

Let cats =  _.groupBy(items, item => item.aligngrp2);

UPDATE

I appreciate @Maria-Elena 's solution, it prevents using a huge library as lodash, if it works I advice using it instead of my solution

Example code to display, I didn't try the code :

cats.map((item, index) => { return ( <div key={index}> <strong>{item.aligngpr2}</strong> { Object.keys(item).map((key, i) => { return ( <ul ><li>{item[Key]}</li></ul> ) }) } </div> ) }


来源:https://stackoverflow.com/questions/60994548/get-return-function-to-display-the-categorized-results-on-the-web-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!