我有一个对象对象,我想更改对象的键
"opening_hours": {
"0": {
"close": "17:00:00",
"is_open": true,
"open": "09:00:00"
},
"1": {
"close": "17:00:00",
"is_open": true,
"open": "09:00:00"
},
"2": {
"close": "17:00:00",
"is_open": true,
"open": "09:00:00"
},
"3": {
"close": "17:00:00",
"is_open": true,
"open": "09:00:00"
},
"4": {
"close": "17:00:00",
"is_open": true,
"open": "09:00:00"
},
"5": {
"is_open": false
},
"6": {
"is_open": false
}
}
喜欢:“ 0”,我希望它是“星期一”,这在Java语言中可能吗?
预期输出为:
{
"monday": {
"close": "17:00:00",
"is_open": true,
"open": "09:00:00"
},
"tuesday": {
"close": "17:00:00",
"is_open": true,
"open": "09:00:00"
},
"wednesday": {
"close": "17:00:00",
"is_open": true,
"open": "09:00:00"
},
"thursday": {
"close": "17:00:00",
"is_open": true,
"open": "09:00:00"
},
"friday": {
"close": "17:00:00",
"is_open": true,
"open": "09:00:00"
},
"saturday": {
"is_open": false
},
"sunday": {
"is_open": false
}
}
答案 0 :(得分:3)
创建一个days
数组,该数组的项目索引与日期相同(例如:0
的{{1}},依此类推)。像这样循环遍历monday
对象的键,并将新的键值对添加到输出中:
opening_hours
您也可以map
对象的entries
并将数字更新为const days = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"],
opening_hours = {"0":{close:"17:00:00",is_open:true,open:"09:00:00"},"1":{close:"17:00:00",is_open:true,open:"09:00:00"},"2":{close:"17:00:00",is_open:true,open:"09:00:00"},"3":{close:"17:00:00",is_open:true,open:"09:00:00"},"4":{close:"17:00:00",is_open:true,open:"09:00:00"},"5":{is_open:false},"6":{is_open:false}},
output = {};
for(const key in opening_hours)
output[days[key]] = opening_hours[key];
console.log(output)
以获取字符串。然后使用Object.fromEntries()
创建一个新对象。
days[number]