上述問題的解決方案是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);
'[ '舊', '新', '模板']圖((X,I)=>({ID:i + 1的,名稱:X}))。' – yurzui
我怎樣將其映射到一個新的對象數組? –
@notyetdecided回答代替yurzui ...簡單地:'讓newArr = [ '舊', '新', '模板']圖((X,I)=>({編號:i + 1的,名稱:X }))':) – Alex