Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
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

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

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)
over 4 years ago · Santiago Trujillo Denunciar

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)

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda