Typescript将json const转换为接口类型

时间:2017-08-31 10:38:35

标签: javascript typescript lodash

我想转换以下const json:

function MyFunction() {
var sourceData = SpreadsheetApp.getActive().getSheetByName("Prova");
var destinationData = SpreadsheetApp.getActive().getSheetByName("Copia di Prova");
var lastRow = sourceData.getLastRow();
var data = sourceData.getRange(1, 1, lastRow, 1).getValues();
for(var i=0;i<data.length;i++)
{
 if (data[i][0] == "RU") {
   var filteredRow = sourceData.getRange(i+1,1,1,5).getValues();
   destinationData.appendRow(filteredRow);
  }
}
}

到这个接口类型:

export const iconRegistry = {
  home: {
    ciclogoc: 'cic-c',
    ciclogoi: 'cic-i',
    ciclogont: 'cic-nt'
  },
};

所以家应该是关键,值应该是ciclogoc,图标应该是cic-c。

这就是我现在所拥有的,但它无法正常工作:

export interface IconDescription {
key: string;
value: string;
icon?: string;
}

2 个答案:

答案 0 :(得分:0)

你通过iconRegistry循环两次:

public getIcons(): IconDescription[] {
    let result: IconDescription[] = [];
    for (let key in iconRegistry) { // loop 1
        result = _.map(iconRegistry, item => { // loop 2
            let icons: IconDescription[] = [];
            for (let value in item) {
                console.log('KEY:', key, 'VALUE:', value, 'ICON:', item[value]);
                icons.push({ key, value, icon: item[value] });
            }
            return icons;
        });
    }
    return result;
}

我重写了你的代码(未经过测试)

public getIcons(): IconDescription[] {
    let result: IconDescription[] = [];
    for (let key in iconRegistry) { //loop through the iconRegistry
        for (let icon in key) { // loop thourgh the icons under the key
            // fill the icon object and add it to the result set
            let icon: IconDescription = {}; 
            icon.key = key;
            icon.value = icon;
            icon.icon = key[icon];
            result.push(icon);
        }        
    }
    return result;
}

答案 1 :(得分:0)

所以经过一些帮助后我终于得到了它。我遍历所有图标,然后再遍历所有值,并将它们推送到IconDescription。

  public getIcon(): IconDescription[] {
    for (let key in iconRegistry) {
        for (let value in iconRegistry[key]) {
            this.icons.push({ key, value, icon: iconRegistry[key][value] });
        }
    }
      return this.icons;
  }