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
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:
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)
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)