是否有一个示例,说明如何使用map遍历打字稿中的复杂元素?

时间:2019-02-01 02:11:43

标签: json typescript

我试图遍历具有“内部对象”的复杂对象。使用地图,我只能下一层。我如何在下面的级别中使用map和typescript循环。当我使用地图进入第二级时,它给了我错误。

JSON中的

结构

{
  "PAYMENTS": [
    {
      "id": 1,
      "userID": 1,
      "month": "March 2015",
      "details": {
        "item1": {
          "amount": "1000",
          "date": "01/03/2015",
          "id": 2
        },
        "item2": {
          "amount": "2000",
          "date": "03/03/2015",
          "id": 3
        }
      }
    },
    {
      "id": 2,
      "userID": 1,
      "month": "April 2015",
      "details": {
        "item1": {
          "amount": "100",
          "date": "01/04/2015",
          "id": 1
        }
      }
    }
  ]
}

我已经创建了2个界面

export interface IPaymentDetailEntity {
  id: number;
  date: Date;
  amount: string;
}

export interface IPaymentEntity {
  id:number;
  month:string;
  userID:number;
  details:IPaymentDetailEntity[]
}

为了遍历对象,我正在尝试

{payments.map(paymentDetails => (
  <div key={paymentDetails.id}>
    {paymentDetails.month} {paymentDetails.userID}
  //this part is not working  {paymentDetails.details.map(item => (
      <div key={item.id}>
        <span>{item.date}</span>
        <span>{item.amount}</span>
      </div>
    ))}

1 个答案:

答案 0 :(得分:0)

details不是数组而是对象,因此在IPaymentEntity接口中将details:IPaymentDetailEntity []更改为details:IPaymentDetailEntity

更改

   export interface IPaymentEntity {
        id:number;
        month:string;
       userID:number;
       details:IPaymentDetailEntity[]
   }

收件人

  export interface IPaymentEntity {
        id:number;
        month:string;
       userID:number;
       details:IPaymentDetailEntity
   }

然后,您可以使用Object.key遍历详细信息对象并在其上进行.map以获得ID,日期和类似以下项的数量

   {payments.map(paymentDetails => (
    <div key={paymentDetails.id}>
         {paymentDetails.month} {paymentDetails.userID}
        {paymentDetails.details && Object.keys(paymentDetails.details).map(detail=> (
          <div key={paymentDetails.details[detail].id}>
              <span>{paymentDetails.details[detail].date}</span>
              <span>{paymentDetails.details[detail].amount}</span>
         </div>
     ))}