Home > OS >  Get an array of items from an object- typescript
Get an array of items from an object- typescript

Time:03-24

I have an object with the below structure:

  Order: [
    {
      id: '001',
      type: '',
      status: '',
      users: [
        {
          OrderId:'001', 
          userId: 'String',
          user: {
            email: 'string',
            givenName: 'Name',
            lastName: 'LastName',
            phone: 'string',
          },
        },
      ],
  
    },

the order is of type Order[] and users of type UserData[]

  type Order
  @model
  @key(fields: ["organizationId", "id"])
  @auth(
    rules: []
  ) {
  id: ID!
  type: OrderType
  status: OrderStatus

  userConnections: [UserOrderConnection] @connection(keyName: "byOrder", fields: ["id"])

  organizationId: ID!
}

type UserOrderConnection
  @model
  @key(fields: ["organizationId", "id"])
  @key(name: "Order", fields: ["OrderId"], queryField: "userOrderByOrder")
  @auth(
    rules: []
  ) {
  id: ID!
  accepted: Boolean
  OrderId: ID!
  Order: Order @connection(fields: ["organizationId", "id"])
  userId: ID!
  user: UserData
}

Whenever I try to get the list of users per order :

let users = this.Order.users

it says that: users don't exist on type Order[], can anyone explain for me why.

CodePudding user response:

Order is an array of objects, you need to get the first element like Order[0] then access .users

let users = this.Order[0].users

A good refresher might help here; How can I access and process nested objects, arrays or JSON?

CodePudding user response:

Order is an Array containing objects. To access users you would need to access item at index [0] if it has property ?.users.

this.Order[0]?.users
  • Related