2017-08-09 62 views
0

我想使用Lodash獲取同一行中顯示的字符串的兩個對象?或者可以使用鏈(_chain(vehicle).get('test')。get('test2))。React JS lodash獲取相同的功能

這是樣品JSON文件

 { 
     "results": [ 
     { 
      "vehicle": { 
      "plate_no": "ABC 1234", 
      "model": "Toyota Innova" 
      } 
     } 
     ] 
    } 

我使用的材料的UI卡和我的代碼看起來是這樣的。

{_.map(this.state.vehicle, (d, idx) =>{ 
    return(
    <Col xs={6} style={{margin: '20px 0 5px' }}> 
     <Card key={d.id}> 
     <CardHeader 
      avatar="http://lorempixel.com/100/100/nature/" 
      title={_.get(d.vehicle, 'model') - _.get(d.vehicle, 'plate_no')} 
      actAsExpander={true} 
      showExpandableButton={true} 
      style={{backgroundColor: Colors.grey200}} 
     /> 

我的目標是顯示標題看起來像這樣。

豐田伊諾 - ABC 1234

回答

1

可以使用_.at()你想要的屬性數組,通過你想要他們,爲了然後陣列#加入他們的行列:

const d = { 
 
    "vehicle": { 
 
    "plate_no": "ABC 1234", 
 
    "model": "Toyota Innova" 
 
    } 
 
}; 
 

 
const result = _.at(d.vehicle, ['model', 'plate_no']).join(' - '); 
 

 
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

代替使用lodash,您可以使用簡單的解構(代碼未測試):

{_.map(this.state.vehicle, ({ vehicle: { model, plate_no } }, idx) =>{ // destructure the vehicle object 
    return(
    <Col xs={6} style={{margin: '20px 0 5px' }}> 
     <Card key={d.id}> 
     <CardHeader 
      avatar="http://lorempixel.com/100/100/nature/" 
      title={`${model} - ${plate_no}`} // use the destructured props 
      actAsExpander={true} 
      showExpandableButton={true} 
      style={{backgroundColor: Colors.grey200}} 
     /> 
+0

謝謝男人:)它有效,但不知何故?你不能使用兩個lodash功能? –

+0

你總是可以使用2個lodash函數 - '_.get()'就像你在模板字符串''{{。get 'plate_no')}'。 –

+0

感謝您的幫助:) –