Home > Mobile >  How to filter an array of object in Vuejs typescript
How to filter an array of object in Vuejs typescript

Time:06-09

in this project. I'm using Vuejs Typescript and the data type is like:

["order":
  {
    "id":1,
    "created_at":"2019-12-06T10:22:17Z",
    "status":"open",
    "updated_at":"2020-07-27T04:21:06Z",
    "recipient":null,
    "custom_fields":[
      {"id":2,"value":'ABC'},
      {"id":3,"value":'EFG},
      {"id":4,"value":'CSA'}
    ]
  }
]

This is how I get the data:

private mapUnprinted (data: any) : IUnprintedSet {
    const result: IUnprintedSet = { orders: [], pagination: {} }
    if (data) {
      data.forEach((anUnprinted: any) => {
        const order: IUnprinted = {
          id: anUnprinted.id,
          created_at: anUnprinted.created_at,
          status: anUnprinted.status,
          updated_at: anUnprinted.updated_at,
          recipient: anUnprinted.recipient,
          custom_fields:  anUnprinted.custom_fields
          // filter((item: any) => item.custom_fields.id === '3'),
        }
        result.orders!.push(order);
      })
      result.pagination = {
        currentPage: data.pagination ? data.pagination.currentPage : undefined,
        pageSize: data.pagination ? data.pagination.pageSize : undefined,
        totalPages: data.pagination ? data.pagination.totalPages : undefined,
        totalResults: data.pagination? data.pagination.totalResults : result.orders!.length
      }
    }
    return result
  }

I added

filter((item: any) => item.custom_fields.id === '3'),

But seems like its not working. End up it return me empty array. The whole issue is i wanna get the value from custom_fields where the ID is equal to 3

This is the return custom_fields: anUnprinted.custom_fields.filter((item: any) => item.id === '3'),

"order": {
      "id": 1,
      "created_at": "2019-12-06T10:22:17Z",
      "status": "open",
      "updated_at": "2020-07-27T04:21:06Z",
      "recipient": null,
      "custom_fields": []

CodePudding user response:

Your id is number not string so maybe:

item.custom_fields.id === 3

or

item.custom_fields.id == '3'

CodePudding user response:

Your data type aren't the same, data type in your id used are number but inside filter() u checked for string

I'm new here, just trying to improve my skill.Do correct me if I’m wrong

  • Related