2017-05-30 123 views
0

比方說,我有一個數組如下:在Angular 2中將字符串數組轉換爲對象數組的最佳方式是什麼?

types = ['Old', 'New', 'Template']; 

我需要把它轉換成對象的數組,看起來像這樣:

[ 
    { 
     id: 1, 
     name: 'Old' 
    }, 
    { 
     id: 2, 
     name: 'New' 
    }, 
    { 
     id: 3, 
     name: 'Template' 
    } 
] 
+4

'[ '舊', '新', '模板']圖((X,I)=>({ID:i + 1的,名稱:X}))。' – yurzui

+0

我怎樣將其映射到一個新的對象數組? –

+0

@notyetdecided回答代替yurzui ...簡單地:'讓newArr = [ '舊', '新', '模板']圖((X,I)=>({編號:i + 1的,名稱:X }))':) – Alex

回答

0

您可以使用地圖遍歷原始數組並創建新對象。

let types = ['Old', 'New', 'Template']; 

let objects = types.map((value, index) => { 
    return { 
    id: index + 1, 
    name: value 
    }; 
}) 

您可以檢查工作的例子here

+0

我試過,但結果數組包含對象,其ID是正確的,但名稱字段包含ID和名稱字段的另一個對象,而不僅僅是字符串。 –

+0

這是不可能發生的,除非在類型數組中有字符串。我添加了一個工作場所鏈接,您可以在其中查看解決方案的工作情況:) – toskv

+0

對不起,你是對的。測試時我正在試驗錯誤的陣列。謝謝。 –

0

上述問題的解決方案是JavaScript或類型腳本的map()方法。

map()方法創建一個新數組,其中調用 的結果爲調用數組中的每個元素提供的函數。

let newArray = arr.map((currentvalue,index,array)=>{ 
return Element of array 
}); 
/*map() method creates a new array with the results of calling 
a provided function on every element in the calling array.*/ 

    let types = [ 
     'Old', 
     'New', 
     'Template' 
     ]; 


    /* 
    let newArray = arr.map((currentvalue,index,array)=>{ 
     return Element of array 
    }); 
    */ 


    let Obj = types.map((value, i) => { 
     let data = { 
       id: i + 1, 
       name: value 
      }; 

     return data; 
    }); 

    console.log("Obj", Obj); 

請按照下面的鏈接:

TypeScript

JS-Fiddle

我們可以實現上述問題通過循環解決方案:

let types = [ 
    "One", 
    "Two", 
    "Three" 
]; 

let arr = []; 

for (let i = 0; i < types.length; i++){ 
    let data = { 
     id: i + 1, 
     name: types[i] 
    }; 
    arr.push(data); 
} 

console.log("data", arr); 
相關問題