2016-10-20 19 views
0

我試圖迭代這個JSON,所以我可以創建一個表,但是因爲有很多標題和許多數據,我怎麼能通過而不做這個。我如何迭代這個json和React中的地圖來渲染它

const BBDDCustomer = { 
     ui_labels: { 
     name: 'Name', 
     address: 'address', 
     postalCode: 'Postal Code', 
     city: 'City', 
     country: 'Country', 
     telephone: 'Telephone', 
     email: 'Email', 
     modified: 'Modified', 
     delete: 'Delete' 

     }, 
    data: [ 
    { 
     name: 'n1', 
     address: 'a1', 
     postalCode: 'PC 1', 
     city: 'c 1', 
     country: 'cou 1', 
     telephone: 'tel 1', 
     email: 'em 1' 
    } 
} 

我沒有寫這樣的:

<table striped bordered condensed hover responsive> 
     <thead> 
     <tr> 
     <th>{BBDDCustomer.ui_labels.name}</th> 
     <th>{BBDDCustomer.ui_labels.address}</th> 
     <th>{BBDDCustomer.ui_labels.postalCode}</th> 
     <th>{BBDDCustomer.ui_labels.city}</th> 
     <th>{BBDDCustomer.ui_labels.country}</th> 
     <th>{BBDDCustomer.ui_labels.telephone}</th> 
     <th>{BBDDCustomer.ui_labels.email}</th> 
     <th>{BBDDCustomer.ui_labels.modified}</th> 
     <th>{BBDDCustomer.ui_labels.delete}</th> 
     </tr> 
</table> 
+2

它不是* JSON *> [什麼?](http://stackoverflow.com/questions/2904131/json-and-object-literal-notation之間的區別是什麼) –

+0

你可以使用'Object.keys'和'map'結合使用。但屬性的順序不能保證。 –

+0

答案在於這個問題,不是嗎?映射你的結構和渲染。你需要學會做出這樣的反應 –

回答

0

您需要在以枚舉屬性,你想

const columns = ['name', 'address', ...]; 

,並使用map

<Table striped bordered condensed hover responsive> 
     <thead> 
     <tr> 
      { 
      columns.map(column => (
       <th key={column}>{BBDDCustomer.ui_labels[column]}</th> 
      )) 
      } 
     </tr> 
     </thead> 
     <tbody> 
     { 
      BBDDCustomer.data.map((data, i) =>(
      <tr key={i}> 
       { 
       columns.map(column => (
        <td key={column + i}>{data[column]}</td> 
       )) 
       } 
      </tr> 
     )) 
     } 
     </tbody> 
</Table> 
+0

Yury是現貨。這是他的方法的一個變種:http://codepen.io/PiotrBerebecki/pen/jrQZvA –