2017-04-25 168 views
-2
let Array: any = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] 

我怎麼可以轉換這個數組爲對象象下面這樣:創建基於陣列的JavaScript對象

let Object: any = { 
    time: { 
     headerName: "" 
    }, 
    monday: { 
     headerName: "Monday" 
    }, 
    tuesday: { 
     headerName: "Tuesday" 
    }, 
    wednesday: { 
     headerName: "Wednesday" 
    }, 
    thursday: { 
     headerName: "Thursday" 
    }, 
    friday: { 
     headerName: "Friday" 
    }, 
    saturday: { 
     headerName: "Saturday" 
    }, 
    sunday: { 
     headerName: "Sunday" 
    } 
}; 

任何想法的傢伙?對不起,剛接觸JavaScript的人很安靜。我怎麼寫一個for循環,以便我可以實現這個結果?在此先感謝球員

+2

你嘗試過什麼嗎? –

+0

是的,試着循環遍歷數組。但我卡在對象部分 – blackdaemon

+0

不知道如何繼續。是否我用我期望的數據結構聲明對象 – blackdaemon

回答

3

只是試試這個

var any = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] 
 
var outputObj = { //create a new object with one default value 
 
    time: { 
 
    headerName: "" 
 
    } 
 
}; 
 
any.forEach(function(item) { //iterate the any array and then keep adding key and values to new Object 
 
    outputObj[item] = { 
 
    headerName: capitalizeFirstLetter(item) 
 
    }; 
 
}); 
 

 
function capitalizeFirstLetter(string) { 
 
    return string.charAt(0).toUpperCase() + string.slice(1); 
 
} 
 

 
console.log(outputObj);

+0

非常感謝Gurvinder。我可以知道什麼是「任何」陣列? – blackdaemon

+0

@blackdaemon它是具有星期幾名稱的數組,因爲它在您的問題中給出。 – gurvinder372

+0

哦,你的意思是'陣列'。可以感謝Gurvider – blackdaemon

3

var result = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"].reduce(function (acc, element) { 
 
    acc[element] = {}; 
 
    acc[element].headerName=element; 
 
    return acc; 
 
}, {time: ""}); 
 
console.log(result);

您可以使用reduce轉換在JavaScript中的對象。

any.reduce(function (acc, element) { 
    acc[element] = {}; 
    acc[element].headerName=element; 
    return acc; 
}, {time: ""}) 
+0

請在發佈前嘗試運行它! –

+0

現在好多了:) –

+0

對不起,只是我的想法。我很快修復了我的代碼:) –

2

var any = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]; 
 

 
var res ={}; 
 
res['time'] ={headername:""}; 
 
any.map(function(a){ 
 
res[a] = {headername:a} 
 

 
}) 
 
console.log(res)

0
Using For loop. 

function toObject(arr) { 
 
    var rv = {}; 
 
    for (var i = 0; i < arr.length; ++i) 
 
    if (arr[i] !== undefined) rv[arr[i]] = {"headerName":arr[i]}; 
 
    console.log(rv); 
 
} 
 
toObject(["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]);