将两个 JSON 数据合并为一个具有特定键值的数据

IT技术 json reactjs
2021-05-12 06:03:36

我有两个 CSV 文件:

球数据.json

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

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

法院.json:

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

如何根据球场 ID 映射球的颜色?例如:2001 --> 红色,2005 --> 蓝色

我尝试了以下方法

    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}
    )}
1个回答

你可以像下面那样做

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

否则在下面使用

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

//Result

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

工作示例https://codesandbox.io/s/react-example-b7bfm