如何同时读取两个JSON文件并使用map在一个表中显示它们?我需要显示一个JSON文件的前3列,然后显示另一个JSON文件的后2列
状态JSON
[{"$class":"org.example.empty.AidShipment","pid":"143","shipment":"68","checkpoints":[],"startingpoint":"isb","destination":"china"},
{"$class":"org.example.empty.AidShipment","pid":"144","shipment":"68","checkpoints":[],"startingpoint":"isb","destination":"china"},
{"$class":"org.example.empty.AidShipment","pid":"14","shipment":"69","checkpoints":["Received","Received"],"startingpoint":"isb","destination":"china"}]
pdetails JSON
[{"pid":144,"package_details":"tea","sp_id":68},
{"pid":143,"package_details":"coffee","sp_id":68},
{"pid":14,"package_details":"trees ","sp_id":69}]
检查点数组中最多可以有4个检查点 我想显示一个表格,其标题为1)pid 2)软件包详细信息3)Checkpoint1 4)Checkpoint2 5)Checkpoint3 6)Checkpoint4 react js中使用map的ship_id 68
答案 0 :(得分:0)
如果文件是静态的,则可以将其导入到项目中,并带有如下所示的文件的相对路径:
import { status } from './status';
如果以后需要更新文件,则可以使用许多库之一进行ajax调用。 React最受欢迎的一些是Axios,the Fetch API或jQuery
要合并数组,可以将其中一个数组与索引映射,并与另一个具有相同索引的数组中的元素联合,如下所示:
status.map((status, index) => ({...status, ...pdetails[index]}))
然后,您将得到一个对象数组,这些对象具有两个数组的所有属性。
要为您的表创建行,可以使用以下命令:
const rows = (
status
.map((status, index) => ({...status, ...pdetails[index]}))
.map(info => (
<tr>
<td>{info.pid}</td>
<td>{info.startingpoint}, {info.destination}</td>
<td>{info.checkpoints[0]}</td>
<td>{info.checkpoints[1]}</td>
<td>{info.checkpoints[2]}</td>
<td>{info.checkpoints[3]}</td>
</tr>
)
)
)
答案 1 :(得分:0)
您可以使用ES2015组合两个json数组(请参阅这篇文章:Combine json arrays by key, javascript),然后使用Lasse Sviland的答案(如此处所示,请运行snnipet):
const statusJSON = [{"$class":"org.example.empty.AidShipment","pid":"143","shipment":"68","checkpoints":[],"startingpoint":"isb","destination":"china"},
{"$class":"org.example.empty.AidShipment","pid":"144","shipment":"68","checkpoints":[],"startingpoint":"isb","destination":"china"},
{"$class":"org.example.empty.AidShipment","pid":"14","shipment":"69","checkpoints":["Received","Received"],"startingpoint":"isb","destination":"china"}]
const pdetailsJSON = [{"pid":144,"package_details":"tea","sp_id":68},
{"pid":143,"package_details":"coffee","sp_id":68},
{"pid":14,"package_details":"trees ","sp_id":69}]
const rows = (
statusJSON
.map(x => Object.assign(x, pdetailsJSON.find(y => y.pid == x.pid)))
.map(info => (
<tr key={info.pid}>
<td>{info.pid}</td>
<td>{info.package_details}</td>
<td>{info.checkpoints[0]}</td>
<td>{info.checkpoints[1]}</td>
<td>{info.checkpoints[2]}</td>
<td>{info.checkpoints[3]}</td>
</tr>
)
)
)
const table = (
<table>
<thead>
<tr>
<td>pid</td>
<td> package details</td>
<td>Checkpoint1</td>
<td>Checkpoint2</td>
<td>Checkpoint3</td>
<td>Checkpoint4</td>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
)
ReactDOM.render(<div>{table}</div>, document.getElementById('root'))
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>