Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

ReactJS: Need help debugging

I have a set of data:

+----+---------+--------+---------------------+
| id | goal_id | saved  | date                |
+----+---------+--------+---------------------+
|  1 |       1 |  50.00 | 2020-12-24 02:35:04 |
|  2 |       2 | 100.00 | 2020-12-24 02:35:04 |
|  3 |       3 | 500.00 | 2020-12-24 02:35:04 |
|  4 |       3 |  10.00 | 2020-12-24 02:35:04 |
|  5 |       3 |  50.00 | 2020-12-24 02:35:04 |
|  6 |       3 | 300.00 | 2020-12-24 02:35:04 |
+----+---------+--------+---------------------+

That belongs to another data set:

+----+--------+------------+
| id | myGoal | goal       |
+----+--------+------------+
|  1 | House  | 1000000.00 |
|  2 | Car    |   21000.00 |
|  3 | School |   13000.00 |
+----+--------+------------+

I've mapped it through the front end:

        {saveData &&
      saveData.map((saveItem) => {
        return (
          <div className="card">
            <ul className="card__list" key={saveItem.id}>
              <SaveCard key={saveItem.id} saveItem={saveItem} />
            </ul>
          </div>
        );
      })}

and now I'm trying to group them by with their respected ID's :

  const [goalRemainder, setGoalRemainder] = useState([saveItem]);

  const saveID = goalRemainder.reduce((savedAmount, { goal_id, saved }) => {
    (savedAmount[goal_id] = savedAmount[goal_id] || []).push(saved);
    return savedAmount;
  }, {});

My output looks like :

{1: Array(1)} 1: [50]
{2: Array(1)} 2: [100]
{3: Array(1)} 3: [500]
{3: Array(1)} 3: [10]
{3: Array(1)} 3: [50]
{3: Array(1)} 3: [300]

Instead I want :

{1: [50]}
{2: [100]} 
{3:[500, 10, 50, 300]} 

My question is, where have I gone wrong?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

please refer to this code piece: https://codesandbox.io/s/dreamy-dew-0vlj5?file=/src/App.js for your expected output.

const saveItem = [
    {
      goal_id: 1,
      saved: 1
    },
    {
      goal_id: 1,
      saved: 2
    },
    {
      goal_id: 2,
      saved: 3
    },
    {
      goal_id: 3,
      saved: 4
    },
    {
      goal_id: 3,
      saved: 1
    }
  ];
  const [goalRemainder, setGoalRemainder] = useState(saveItem); // no array brackets here

  const savedAmount = {};
  const saveID = goalRemainder.reduce((savedAmount, { goal_id, saved }) => {
    (savedAmount[goal_id] = savedAmount[goal_id] || []).push(saved);
    return savedAmount;
  }, {});
  console.log(saveID);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...