【问题标题】:extract object from array - typescript从数组中提取对象 - 打字稿
【发布时间】:2020-10-05 21:52:53
【问题描述】:

我有一个如下所示的行程对象:

Array (1)
0 {id: 1, vehicle: {freeSeats: 2, __typename: "Vehicle"}, startLocation: "{\"type\":\"Point\",\"coordinates\":[8.217462,53.13975]}", endLocation: "{\"type\":\"Point\",\"coordinates\":[8.258844,53.119525]}", timeOfDeparture: "2020-06-16T11:48:00.869Z", …}
type TripListProps = {
  trips: any; //TODO FIX
  //trips: Array<Trip>,
  friendIds: Array<number>,
};

export const TripList: React.FunctionComponent<TripListProps> = ({ trips, friendIds }) => {
  console.log('trips', trips);
  if (trips.length > 0) {
    return ( 
      <View style={{ height: 500 }}>
        <FlatList
          data={trips}
          horizontal={false}
          scrollEnabled
          renderItem={({ item }) => <TripContainer trip={item} friendIds={friendIds} />}
          keyExtractor={(trip: any) => trip.id.toString()}
        />
      </View>
    )
  } else {
    return (<View style={styles.noTripsFound}>
    <Text style={styles.text}>No trips found</Text></View>);
  }
};

它的原始类型是Array&lt;Trip&gt;。但是,这里我将它传递给另一个组件TripContainer,这需要trip 采用这种形式:

trip: {
  driver: {
      firstName: string;
      rating: number;
      id: number;
  };
  timeOfDeparture: any;
}

因此,如果我将 TripListPropstrips: any 更改为 trips: Array&lt;Trip&gt;,我会收到错误消息。

有什么方法可以从整个数组对象中只提取这部分吗?

【问题讨论】:

    标签: javascript reactjs typescript react-native prop


    【解决方案1】:

    您可以在lodash 中使用_.pick 来只选择那些有钥匙的人

    var object = { 'a': 1, 'b': '2', 'c': 3 };
    
    _.pick(object, ['a', 'c']);
    // => { 'a': 1, 'c': 3 }
    

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 1970-01-01
      • 2019-04-23
      • 2018-08-20
      • 2018-07-03
      • 2023-03-28
      • 2022-01-12
      • 2018-08-31
      相关资源
      最近更新 更多