问题
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
courtdatahasball_in_use(e.g '3') which is not linked with any fromballdata.balldataandcourtdataarray are shuffled.balldataandcourtdataarray 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