[英]How do I loop through an array of objects to add objects for missing values
I have a bar chart with data filtered by week (Sun-Sat).我有一个条形图,其中包含按周(周日至周六)过滤的数据。 However, when a "day" is missing I get an empty space in the graph and I would like to fill that day with the value of "0".
但是,当缺少“一天”时,我会在图中得到一个空白区域,我想用“0”值填充那一天。
Code and data:代码和数据:
const data = [{value: 2, createdDate: "20201025", day: "Sun" }, {value: 7, createdDate: "20201027", day: "Tue", {value: 5, createdDate: "20201028", day: "Wed"}];
const startOfWeek = moment().startOf('isoWeek');
const endOfWeek = moment().endOf('isoWeek');
const currentWeek = data.filter((e) => moment(e.date) >= startOfWeek && moment(e.date) <= endOfWeek);
How do I add Mon, Thu, Fri, and Sat with values of 0 to the currentWeek array?如何将值为 0 的 Mon、Thu、Fri 和 Sat 添加到 currentWeek 数组中?
Make an array of weekdays you want to test:制作要测试的工作日数组:
const weekdays = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
Loop through them, adding a "zero" event to currentWeek
whenever it doesn't contain that weekday:循环遍历它们,在
currentWeek
不包含该工作日时向它添加一个“零”事件:
weekdays.forEach( function(weekday) {
let found = false; // assume
for ( var i=0; i < currentWeek.length; i++ ) {
if ( currentWeek[i].day == weekday ) {
found = true;
break;
}
}
// weekday isn't in currentWeek, so add it:
if ( ! found ) {
currentWeek = currentWeek.concat( { value: 0, day: weekday } );
}
} );
Actually I think you could think it from another perspective.其实我觉得你可以换个角度思考。
First you fake an array of each day like below:首先你伪造一个每天的数组,如下所示:
{value: 0, createdDate: "20201001", day: "Sun" }
After that you can merge two array together.之后,您可以将两个数组合并在一起。
If the order of your days in the array doesn't matter, this is how I would do it:如果您在数组中的日期顺序无关紧要,那么我将这样做:
// create an array of short weekdays from moment
const weekdays = moment.weekdaysShort();
// iterate over the days
for (const day of weekdays) {
// check if this day does not exist in the current week
if (!currentWeek.find(el => el.day == day)) {
// if not, add it
currentWeek.push({value: 0, day});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.