jason1234
jason1234

Reputation: 213

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}
    )}

Upvotes: 0

Views: 487

Answers (1)

harish kumar
harish kumar

Reputation: 1759

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

Upvotes: 1

Related Questions