簡體   English   中英

JSON 具有“from”和“to”屬性的對象數組,並按時間段分組

[英]JSON array of objects with properties “from” and “to” and group it by time period

如果數組中的日期相交,則 function 應將它們合並為一個時期,否則時期應分開

 var dates = [ { "from":"03/01/2021", "to":"03/05/2021" }, { "from":"03/08/2021", "to":"03/10/2021" }, { "from":"03/07/2021", "to":"03/20/2021" } ]; var item = dates; var index = 0; var out = document.querySelector('#test'); for(var i = 0; i < item.length; i++){ index++; var from_i = Date.parse(item[i].from); var to_i = Date.parse(item[i].to); var from_index = Date.parse(item[index].from); var to_index = Date.parse(item[index].to); if(from_index >= from_i && from_index <= to_i){ let updated_from = new Date(from_index); let update_to = new Date(to_index); console.log(updated_from); out.innerHTML += updated_from.toDateString() + update_to.toDateString() + "<br/>"; } }
 <div id="test"> </div>

傳入案例 jSON: [ { "from":"03/01/2021", "to":"03/06/2021" }, { "from":"03/10/2021", "to":" 2021 年 3 月 15 日"},{"來自":"2021 年 3 月 20 日","到":"2021 年 3 月 25 日"}]

Output:3月1日至5日、7日至20日

有什么幫助嗎? 學習 JS……對我來說有點難(

你可以這樣做

 const data = [ { "from":"03/01/2021", "to":"03/06/2021" }, { "from":"03/10/2021", "to":"03/15/2021" }, { "from":"03/20/2021", "to":"03/25/2021" } ] const monthToString = month => { const months = { '01': 'Jan', '02': 'Feb', '03': 'Mar', '04': 'Apr', '05': 'May', '06': 'Jun', '07': 'Jul', '08': 'Aug', '09': 'Sep', '10': 'Oct', '11': 'Nov', '12': 'Dec', } return months[month] || month } const result = Object.entries(data.reduce((res, {from, to}) => { const [monthFrom, day, year] = from.split('/') const [m, dayTo, y] = to.split('/') const month = monthToString(m) return {...res, [month]: [...(res[month] || []), [day, dayTo]] } }, {})).map(([month, days]) => `${month} ${days.map(([from, to]) => `${parseInt(from)}-${parseInt(to)}`).join(', ')}`).join('\n') console.log(result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM