需要幫助解決這個問題,應該是一個小任務,但想不通。
問題:資料是一組物件,x 為一周的第一個日期,y 為該周的值。需要一個解決方案/函式,它將在 x 中回傳該周的所有日期,并在 y 中為每個日期回傳相同的值。
輸入:
data =
[
{
"x": "2022-07-25",
"y": 0.5
},
{
"x": "2022-08-01",
"y": 0.2
},
{
"x": "2022-08-08",
"y": 0.3
}
]
預期輸出:
data =
[
{
"x": "2022-07-25",
"y": 0.5
},
{
"x": "2022-07-26",
"y": 0.5
},
{
"x": "2022-07-27",
"y": 0.5
},
{
"x": "2022-07-28",
"y": 0.5
},
{
"x": "2022-07-29",
"y": 0.5
},
{
"x": "2022-07-30",
"y": 0.5
},
{
"x": "2022-07-31",
"y": 0.5
},
{
"x": "2022-08-01",
"y": 0.2
},
{
"x": "2022-08-02",
"y": 0.2
},
{
"x": "2022-08-03",
"y": 0.2
},
{
"x": "2022-08-04",
"y": 0.2
},
{
"x": "2022-08-05",
"y": 0.2
},
{
"x": "2022-08-06",
"y": 0.2
},
{
"x": "2022-08-07",
"y": 0.2
},
{
"x": "2022-08-08",
"y": 0.3
},{
"x": "2022-08-09",
"y": 0.3
}
,{
"x": "2022-08-10",
"y": 0.3
}
,{
"x": "2022-08-11",
"y": 0.3
},{
"x": "2022-08-12",
"y": 0.3
},{
"x": "2022-08-13",
"y": 0.3
},{
"x": "2022-08-14",
"y": 0.3
}
]
uj5u.com熱心網友回復:
您可以通過使用和在此答案中找到flatMap
的擴展名來做到這一點addDays
const data = [{
"x": "2022-07-25",
"y": 0.5
},
{
"x": "2022-08-01",
"y": 0.2
},
{
"x": "2022-08-08",
"y": 0.3
}
]
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() days);
return date;
}
const result = data.flatMap(item => {
const date = new Date(item.x)
return [0,1,2,3,4,5,6,7].map(d => (
{
x: date.addDays(d).toISOString(),
y: item.y
}
));
})
console.log(result)
uj5u.com熱心網友回復:
你可以試試reduce
const data = [{
"x": "2022-07-25",
"y": 0.5
},
{
"x": "2022-08-01",
"y": 0.2
},
{
"x": "2022-08-08",
"y": 0.3
}
]
const finalResult = data.reduce((result, current) => {
const {
x,
y
} = current
//convert the string date to a date type
const currentDate = new Date(x)
//add the current date to the result by default
result.push(current)
const days = 6
for (let day = 1; day <= days; day ) {
//change the current date to the next date
currentDate.setDate(currentDate.getDate() 1)
//add the new date data to the result
result.push({
x: currentDate.toISOString().substring(0, 10),
y: y
})
}
return result
}, [])
console.log(finalResult)
uj5u.com熱心網友回復:
嘗試這個!
const expandEveryWeek = function(data){
//Array for result
const result = [];
//Iterate all array parameters (Assuming first element is the first of week)
//It's always Monday
for(const obj of data){
const {x,y} = obj; //Extract values (x,y)
const date = new Date(x); //Create date with x
for(let j=0;j<7;j ){
result.push({ x : date.toISOString().substring(0,10), y}); //Insert first (0 index)
date.setDate(date.getDate() 1) //Add day
}
}
return result;
}
好的,將資料物件傳遞給上述函式。
假設該陣列的每個元素都包含一個日期,該日期始終指示要擴展的星期幾
迭代所有 obj 內部資料并為每一個提取 <date,value>。對于每個日期,迭代其他 7 個步驟(一個用于開始日期,其他 6 個用于接下來的日期,并增加一天的日期,在此之后,將其推入陣列中,其值為 y。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/503789.html
標籤:javascript 数组 javascript 对象 工作日
上一篇:使用jQuery停止影片回圈