Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

86
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!