'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. As you can see they have 1:1 attribute names 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.
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:
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 ?
Thanks guys!
Solution 1:[1]
That
dataObject[objKey] = sh.getRow(idx).getCell(key).value as string
did the trick!. Thanks @yong Shun!
Solution 2:[2]
You can attempt with keyof typeof dataObject.
for (const key in excelStructure.structure) {
let objKey = key as keyof typeof dataObject;
dataObject[objKey] = /* value */;
}
Note: excelStructure.structure[key] returns the value but not key.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wurzelseppi |
| Solution 2 | Yong Shun |
