将两个 JSON 数据合并为一个具有特定键值的数据 [英] Merge two JSON data into one with particular key values
本文介绍了将两个 JSON 数据合并为一个具有特定键值的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个 CSV 文件:
balldata.json
[{"id": "1",红色",},{"id": "2","颜色": "蓝色",}]
court.json:
[{court_id":2001,"ball_in_use": "1",},{court_id":2005,"ball_in_use": "2",}]
如何根据球场 ID 映射球的颜色?例如:2001 --> 红色,2005 --> 蓝色
我尝试了以下方法
const App = (props) =>{让颜色 = balldata.map((c, index) => {返回 c.id + "-" + c.color;})让游戏 = courtdata.map((ball, index) => {返回 ball.ball_in_use;})返回(//不确定要返回什么,因为我无法使用 {color} 或 {game})}
解决方案
你可以像下面这样操作
const result = [courtdata, balldata].reduce((p, q) => p.map((c, i) => Object.assign({}, c, {color: q[i].color})));//结果[{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})))//结果[{2001:红色"},{2005 年:蓝色"}]
工作示例 https://codesandbox.io/s/react-example-b7bfm
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}
)}
解决方案
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
这篇关于将两个 JSON 数据合并为一个具有特定键值的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文