2017-08-31 72 views
0

我想下面的常量JSON轉換:打字稿變換JSON常量的接口類型

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

這種接口類型:

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

所以,家應該是關鍵,價值應該是ciclogoc和圖標應該是cic-c。

這是我現在有,但它不能正常工作:通過您的iconRegistry

public getIcons(): IconDescription[] { 
    let result: IconDescription[] = []; 
    for (let key in iconRegistry) { 
     result = _.map(iconRegistry, item => { 
      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; 
} 

回答

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; 
    } 
0

您循環兩次:

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; 
} 
+0

修復您的代碼,你應該改變_.map(iconRegistry與_.map(iconRegistry [關鍵] – mathewmeconry

+0

遺憾的是它不工作。 – Devid