reactjs doesn't run functions inside Object.assign

自古美人都是妖i 提交于 2020-06-29 03:41:35

问题


Add on to the question here: Merge two JSON data into one with particular key values

balldata.json

[
  {
    "id": "1",
    "color": "red",

  },
  {
    "id": "2",
    "color": "blue",
  }]

court.json:

[
  {
    "court_id": 2001,
    "ball_in_use": "1",
  },
  {
    "court_id": 2005,
    "ball_in_use": "2",
  }]

Now, I want to map two different json data base on it's ID.

so instead of:

const result = [courtdata, balldata].reduce((p, q) => p.map((c, i) => Object.assign({}, {[c.court_id] : q[i].color})))

I tried:

const result = [courtdata, balldata].reduce((p, q) => p.map((c, i) => Object.assign({}, {[c.court_id] : function(){
   console.log("this log did not run at all")
   for(var j=0; j<balldata.length; j++){
      if(i.court_id == balldata.id){
         return balldata[j].color;
      }
   }
}
})))

my output:

return (
    <ul>
      {result.map(r => (
        <li>
          Court id - {r.court_id} | Ball colour - {r.color}
        </li>
      ))}
    </ul>
  );

I did an console.log to see why I didn't get the result I wanted, but it turns out, my function did not run at all. Why is that so? I did the function based on the answer in: Why doesn't an if/else statement work in Object.assign() and .map?


回答1:


As per the problem statement, there will be some use cases

  • courtdata has ball_in_use(e.g '3') which is not linked with any from balldata.
  • balldata and courtdata array are shuffled.
  • balldata and courtdata array are in same order.

For use case 1, in the below example, I'm showing "No color assigned" string to that extra entity. You can remove that as well...

So final code would be :

 const final = [courtdata, balldata].reduce((p, q) =>
        p.map((c, i) => {
          const colored = q.find(val => val.id === c.ball_in_use);
          return {
            ...c,
            color: colored ? colored.color : "no colour assigned"
          };
        })
      );

Example: https://codesandbox.io/s/react-hooks-usestate-dmk5h



来源:https://stackoverflow.com/questions/62507601/reactjs-doesnt-run-functions-inside-object-assign

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