Merge two JSON data into one with particular key values

I have two CSV files:

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",
      }]

How can I map the color of the ball based on the court id? For example:
2001 –> red, 2005 –> blue

I tried below approach

    const App = (props) =>{
        let color = balldata.map((c, index) => {
          return c.id + "-" + c.color;})
        let game = courtdata.map((ball, index) => {
          return ball.ball_in_use;})
        return(
          //not sure what to return here since I am unable to use {color} or {game}
    )}

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You can do it like below

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

// Result

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

else use below

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

//Result

[
 {2001: "red"}, 
 {2005: "blue"}
]

Working example https://codesandbox.io/s/react-example-b7bfm

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply