Angular 11 无法动态访问对象 属性

Angular 11 can't access object property dynamically

我必须访问我的对象属性的子集并将标签和值存储在另一个数组中。基本上我有这个对象:

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

作为输出,我需要一个包含以下类型对象的数组:{label: string, value: number}.
我需要用 prop1 和 prop2 及其值填充这个数组,这样我就有这样的东西:

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

我试过的是这样的:

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

或 this.myObject.l

但是我得到这个错误:

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

我已将“l”的类型更改为字符串,但我得到:

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

正确的做法是什么?

myObject

您可以使用 keyof 代替 any 来告诉 typescript labels 是一个字符串数组,其中字符串是您界面的键:

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)

您可以使用 Object.entries 函数迭代 key/value 对:

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)