[英]Rearrange object key based on array of keys javascript
headers = ["no", "car","color","type"]
//json response
resp = [
{"color":"green", "car":"bmw", "type": "suv", "no":"1"},
{"color":"red", "car":"honda", "type": "sedan", "no":"2"},
{"color":"blue", "car":"vw", "type": "truck", "no":"3"},
]
how can i rearrange the object key:val position based on headers
array, so that i can render them in a table like so:我如何重新排列 object 键:val position 基于headers
数组,以便我可以将它们呈现在这样的表中:
no不 | car车 | color颜色 | type类型 |
---|---|---|---|
1 1 | bmw宝马 | green绿色 | suv越野车 |
2 2 | honda本田 | red红色的 | sedan轿车 |
3 3 | vw大众 | blue蓝色的 | truck卡车 |
I need to use resp
as below to render in a table:我需要使用如下的resp
在表格中呈现:
resp.map((i,k) => (
<tr key={k}>
<td>{i["no"]<td>
<td>{i["car"]<td>
<td>{i["color"]<td>
<td>{i["type"]<td>
<tr>
}))
You dont need to 'order' the json for you to form the table.您无需为您“订购” json 即可形成表格。 JavaScript doesn't guarantee order for objects, unlike arrays.与 arrays 不同,JavaScript 不保证对象的顺序。 You could use map
on resp
to form the table row based on the order of header list.您可以分别使用map
根据resp
列表的顺序形成表格行。
resp.map(data => {
let row = '<tr>'
headers.forEach(header => {
row = row + '<td>' +data[header] + '</td>';
});
return row += '</tr>';
});
You just need to make sure, that the order of the items in headers
is in the same order that you need.您只需要确保headers
中项目的顺序与您需要的顺序相同。
No need to do any arrangement as Object keys in JavaScript aren't guaranteed to follow an order.无需做任何安排,因为 JavaScript 中的 Object 键不保证遵循订单。 If you need data in a particular order, you should use array.如果您需要特定顺序的数据,则应使用数组。
For your current problem, you can iterate the rows
and show it in order set by headers
:对于您当前的问题,您可以迭代rows
并按headers
设置的顺序显示它:
const rows = [ { color: 'green', car: 'bmw', type: 'suv', no: '1' }, { color: 'red', car: 'honda', type: 'sedan', no: '2' }, { color: 'blue', car: 'vw', type: 'truck', no: '3' }, ] const headers = ['no', 'car', 'color', 'type'] function App() { return ( <table border={1}> <tr> {headers.map((header) => ( <th>{header}</th> ))} </tr> {rows.map((row) => ( <tr> {headers.map((header) => ( <td>{row[header]}</td> ))} </tr> ))} </table> ) } ReactDOM.render(<App/>,document.getElementById('mydiv'))
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script> <body> <div id="mydiv"></div> </body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.