How can i iterate through a structure like this in JS , basically it's an array containg an array of objects This is what I get when I console.log it
[Array(1)]
0: Array(1)
0: {day: "Friday", start: "2:00", end: "7:30"}
length: 1
__proto__: Array(0)
length: 1
__proto__: Array(0)
I have tried this
formattedShifts.map(shift => shift.end)
But it fails, formattedShifts it's the array i push into this is where I create the array
let formattedShifts = [];
if(props.formData.isLinkedShifts) {
//converts shift.startTime and shift.endTime format
function toDays(startDateString, endDateString) {
const formatString = 'ddd MMM DD YYYY HH:mm:ss [GMT]ZZ';
const startDate = moment(startDateString, formatString);
const endDate = moment(endDateString, formatString);
const start = startDate.format('H:mm');
const end = endDate.format('H:mm');
const dates = [];
while(startDate.isSameOrBefore(endDate, 'day')) {
let currentDay = startDate.format('dddd');
dates.push({day: currentDay, start: start, end: end});
startDate.add(1, 'days');
}
return dates;
}
formattedShifts.push( toDays( props.formData.shifts.map( shift => shift.startTime),
props.formData.shifts.map( shift => shift.endTime)) );
}
As per your console result, I assuming that your array is something like
Var a = [
{
day: "Friday",
start: "2:00",
end: "7:30"
}
]
So you can traverse through this like,
a.forEach(function(item) {console.log(item)}) //{day: "Friday", start: "2:00", end: "7:30"}
a.forEach(function(item) {
for (i in item) {
console.log(i, item[i])
}
})
Console result will be like
day Friday // i will give the key (day), item[i] will give the value of key (Friday)
start 2:00
end 7:30
As you have added the Array in the question like this:
You need to iterate it:
var a = [[{day: "Friday", start: "2:00", end: "7:30"}, {day: "Friday", start: "2:00", end: "12:30"},{day: "Friday", start: "2:00", end: "8:30"} ,{day: "Friday", start: "2:00", end: "09:30"}]] const ends = a[0].map(value => value.end); console.log(ends)
You need to iterate over the first element of your array of array of object
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.