Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

91
Visualizações
Angular 11 can't access object property dynamically

I have to access to a subset of my object properties and store the label and the value in another array. Basically I have this object:

    myObject: CustomObject {
    prop1: value1,
    prop2: value2
    prop3: value3
    }

and as output I need an array with objects of type: {label: string, value: number}.
I need to fill this array with prop1 and prop2 and their values, so that I have something like this:

    myArray = [{label: prop1, value: value1}, {label: prop2, value: value2}]

What I've tried is this:

    labels = ['prop1', 'prop2'];
    labels.forEach((l: any) => {
      this.myArray.push({ label: l, value: this.myObject[l] })
     })

or also this.myObject.l

But I get this error:

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'MyObject'

I've changed the type of "l" to string but I got:

No index signature with a parameter of type 'string' was found on type

What's the correct way to do this?

myObject

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Instead of any, you can use keyof to tell typescript that labels is an array of strings where strings are the keys of your interface:

Playground Link

interface CustomObject {
    prop1: any;
    prop2: any;
    prop3: any;
}

const myObject: CustomObject = {
    prop1: 1,
    prop2: 2,
    prop3: 3,
}

const labels: (keyof CustomObject)[] = ['prop1', 'prop2'];

const myArray = labels.map(label => ({ label, value: myObject[label] }))
console.log(myArray)
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use Object.entries function to iterate over key/value pairs:

const myObject = { prop1: 'value1', prop2: 'value2', prop3: 'value3' }
let myArray = [];

Object.entries(myObject).map((item)=>{ myArray.push({label:item[0], value:item[1]})})
console.log(myArray)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda