简体   繁体   English

Map json object 中的数据来自与 typescript 的接口

[英]Map json data in object from interface with typescript

I´m trying to put data from an Excel-Sheet into a json object. For this I created a structure Info object for reading the excel, and a Thing interface for the object that should receive the data.我试图将 Excel 工作表中的数据放入 json object。为此,我创建了一个结构信息 object 用于读取 excel,并为 object 创建了一个应该接收数据的事物接口。 As you can see they have 1:1 attribute names Thing:excelStructure.structure如您所见,它们具有 1:1 属性名称 Thing:excelStructure.structure

export const excelStructure: { [key: string]: any } = {
    "headerRow": 1,
    "firstdatarow": 3,
    "structure": {
        "sortierung": "A",
        "stockwerk": "B",
        "raum": "C",
        "objekt": "D",
        "typ": "E",
        "aktor": "F",
        "aktorausgang": "G",
        "ga_schalten": "H",
        "ga_dimmer": "I",
        "ga_helligkeit": "J",
        "ga_schaltzustand": "K",
        "ga_wert": "L",
        "groups": "M",
        "allow_export": "N"
    }
}


export interface Thing{
    sortierung: string
    stockwerk: string
    raum: string
    objekt: string
    typ: string
    aktor: string
    aktorausgang: string
    ga_schalten: string
    ga_dimmer: string
    ga_helligkeit: string
    ga_schaltzustand: string
    ga_wert: string
    groups: string
    allow_export: string

}

Now I want to create a loop in which I read the data from excel and fill the Thing object.现在我想创建一个循环,在其中我从 excel 读取数据并填充 Thing object。

var dataObject:Thing = {
                    ...excelStructure.structure
                } //to initialize the Thing object with something. Don´t know if I need it :-(
                
                for (const key in excelStructure.structure) {
                    dataObject[excelStructure.structure[key]] = sh.getRow(idx).getCell(excelStructure.structure[key]).value

The IDE complains this: IDE 抱怨这个:

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'Thing'.ts(7053)

is there a smooth way to do this without having to map it attribute to attribute myself?有没有一种顺利的方法可以做到这一点,而不必将它归因于我自己的 map?

Thanks guys!多谢你们!

You can attempt with keyof typeof dataObject .您可以尝试使用keyof typeof dataObject

for (const key in excelStructure.structure) {
   let objKey = key as keyof typeof dataObject;
   dataObject[objKey] = /* value */;
}

Sample Typescript Playground 样品 Typescript 游乐场

Note: excelStructure.structure[key] returns the value but not key .注意: excelStructure.structure[key]返回值而不是key

That

dataObject[objKey] = sh.getRow(idx).getCell(key).value as string

did the trick.. Thanks @yong Shun!成功了..谢谢@yong Shun!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM