Home > Net >  Assign a property of nested array inside a new string array
Assign a property of nested array inside a new string array

Time:05-26

I'm new in VueJs and Typescript, so I have four interfaces:

export interface ShipMethodResponse {
  companyTypeList: CompanyType[]
}

export interface CompanyType {
  companyTypeId: string
  companyTypeName: string
  companyList: Company[]
}

export interface Company {
  companyId: string
  companyTypeId: string
  companyName: string
  companyAbbreviation: string
  companyDescription: string
  companyWebsite: string
  shipMethodList: ShipMethod[]
}

export interface ShipMethod {
  shipMethodId: number
  companyId: string
  shipMethodName: string
}

Each one can have an array of the next interface if you read from top to down.

So I want to insert into a new array of a string the property companyName of Company interface, so I try:

data() {
    return {
      shipMethodList: [] as string[],
      ...
    }
  },

  methods: {

    async myMethod() {
      //companyTypeList is a CompanyType array

      var b = companyTypeList.map((e) => ({
        companyList: e.companyList,
      }))

      for (const c of b) {
        var company = c.companyList.map((company) => ({
          companyName: company.companyName,
        }))

        this.shipMethodList.push(company)
      }


    }
    }

But when I try to push the company it is throwing

Argument of type '{ companyName: string; }[]' is not assignable to parameter of type 'string'.

How can I create a list of all "companyName" property? Regards

CodePudding user response:

I think the problem is here:

var company = c.companyList.map((company) => ({
    companyName: company.companyName,
}))

You say you want to create string[], but that map function creates { companyName: string }[]

Change it to this:

var allCompanyNames = c.companyList.map(
    company => company.companyName
)

UPDATE

What you really want is probably this:

for (const c of b) {
    for(company of c.companyList) {
        this.shipMethodList.push(company.companyName)
    }
}
  • Related