Logo
⚠️ Unsaved
[M]:

Accessing Array Fields in Nested Objects

This notebook demonstrates how to access time values from a nested data structure where an array contains objects with date keys and time arrays.

[ ]:
// Define the sample data structure
const times = [
{
'2025-03-10': [
'08:00', '08:15', '08:30', '08:45',
'09:00', '09:15', '09:30', '09:45',
'10:00', '10:15', '10:30', '10:45',
'11:00', '11:15', '11:30', '11:45',
'12:00', '12:15', '12:30', '12:45',
'13:00', '13:15', '13:30', '13:45',
'14:00', '14:15', '14:30', '14:45',
'15:00', '15:15', '15:30', '15:45',
'16:00', '16:15', '16:30', '16:45',
'17:00', '17:15', '17:30', '17:45',
'18:00', '18:15', '18:30', '18:45'
],
'2025-03-11': [
'08:00', '08:15', '08:30', '08:45',
'09:00', '09:15', '09:30', '09:45',
'10:00', '10:15', '10:30', '10:45',
'11:00', '11:15', '11:30', '11:45',
'12:00', '12:15', '12:30', '12:45',
'13:00', '13:15', '13:30', '13:45',
'14:00', '14:15', '14:30', '14:45',
'15:00', '15:15', '15:30', '15:45',
'16:00', '16:15', '16:30', '16:45',
'17:00', '17:15', '17:30', '17:45',
'18:00', '18:15', '18:30', '18:45'
]
}
];

// Examine the structure
console.log("Data structure type:", typeof times, "\n");
console.log("Is times an array?", Array.isArray(times), "\n");
console.log("Length of times array:", times.length, "\n");
[M]:

Method 1: Accessing Times Using Known Date Keys

If you know the specific date keys, you can access the time arrays directly.

[ ]:
// Access times for a specific date using bracket notation
const march10Times = times[0]['2025-03-10'];
console.log("Times for March 10, 2025:\n");
console.log(march10Times, "\n");

// Access times for another date
const march11Times = times[0]['2025-03-11'];
console.log("\nTimes for March 11, 2025:\n");
console.log(march11Times, "\n");

// Access a specific time slot
console.log("\nFirst time slot on March 10:", times[0]['2025-03-10'][0], "\n");
console.log("Last time slot on March 11:", times[0]['2025-03-11'][times[0]['2025-03-11'].length - 1], "\n");
[M]:

Method 2: Accessing Times When Date Keys Are Unknown

If you don't know the date keys in advance, you can extract them dynamically.

[ ]:
// Get all date keys from the first object
const dateKeys = Object.keys(times[0]);
console.log("Available date keys:", dateKeys, "\n");

// Access times for each date
dateKeys.forEach(date => {
console.log(`\nTimes for ${date}:\n`);
console.log(`Total time slots: ${times[0][date].length}\n`);
console.log(`First time: ${times[0][date][0]}\n`);
console.log(`Last time: ${times[0][date][times[0][date].length - 1]}\n`);
});
[M]:

Method 3: Mapping All Times

If you want to map all times from all dates, you can use nested loops or array methods.

[ ]:
// Method 3.1: Using nested forEach loops
console.log("All times using nested forEach loops:\n");
const allTimes1 = [];

times.forEach(timeObj => {
Object.keys(timeObj).forEach(date => {
timeObj[date].forEach(time => {
allTimes1.push({ date, time });
});
});
});

console.log(`Total time slots: ${allTimes1.length}\n`);
console.log("First 5 time slots:\n");
console.log(allTimes1.slice(0, 5), "\n");
[ ]:
// Method 3.2: Using flatMap and map
console.log("All times using flatMap and map:\n");
const allTimes2 = times.flatMap(timeObj => {
return Object.entries(timeObj).flatMap(([date, timeArray]) => {
return timeArray.map(time => ({ date, time }));
});
});

console.log(`Total time slots: ${allTimes2.length}\n`);
console.log("First 5 time slots:\n");
console.log(allTimes2.slice(0, 5), "\n");
[M]:

Method 4: Creating a Formatted Schedule

Let's create a more user-friendly schedule format.

[ ]:
// Create a formatted schedule object
const schedule = times.reduce((result, timeObj) => {
Object.entries(timeObj).forEach(([date, timeArray]) => {
// Format the date (e.g., "2025-03-10" to "Monday, March 10, 2025")
const formattedDate = new Date(date).toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
// Group times by hour
const timesByHour = timeArray.reduce((hourGroups, time) => {
const hour = time.split(':')[0];
if (!hourGroups[hour]) {
hourGroups[hour] = [];
}
hourGroups[hour].push(time);
return hourGroups;
}, {});
result[formattedDate] = timesByHour;
});
return result;
}, {});

console.log("Formatted Schedule:\n");
console.log(JSON.stringify(schedule, null, 2), "\n");
[M]:

Method 5: Finding Available Time Slots

Let's create a function to find available time slots for a specific date.

[ ]:
// Function to find available time slots for a specific date
function getAvailableTimeSlots(date) {
// Find the object containing the date
for (const timeObj of times) {
if (timeObj[date]) {
return timeObj[date];
}
}
return [];
}

// Test the function
const availableTimes1 = getAvailableTimeSlots('2025-03-10');
console.log("Available times for March 10, 2025:\n");
console.log(availableTimes1, "\n");

const availableTimes2 = getAvailableTimeSlots('2025-03-12'); // Non-existent date
console.log("\nAvailable times for March 12, 2025:\n");
console.log(availableTimes2, "\n");
[M]:

Method 6: Filtering Time Slots

Let's create a function to filter time slots based on a time range.

[ ]:
// Function to filter time slots based on a time range
function filterTimeSlots(date, startTime, endTime) {
const timeSlots = getAvailableTimeSlots(date);
return timeSlots.filter(time => {
return time >= startTime && time <= endTime;
});
}

// Test the function
const morningSlots = filterTimeSlots('2025-03-10', '08:00', '12:00');
console.log("Morning time slots (8:00 AM - 12:00 PM) on March 10, 2025:\n");
console.log(morningSlots, "\n");

const afternoonSlots = filterTimeSlots('2025-03-11', '13:00', '17:00');
console.log("\nAfternoon time slots (1:00 PM - 5:00 PM) on March 11, 2025:\n");
console.log(afternoonSlots, "\n");
[M]:

Summary

This notebook has demonstrated several methods to access and manipulate the time fields in your nested data structure:

  1. Direct access with known keys: times[0]['2025-03-10']
  2. Dynamic access with unknown keys: Using Object.keys() to discover date keys
  3. Mapping all times: Using nested loops or array methods to extract all time slots
  4. Creating a formatted schedule: Transforming the data into a more user-friendly format
  5. Finding available time slots: Creating a function to get time slots for a specific date
  6. Filtering time slots: Creating a function to filter time slots based on a time range

The key insight is understanding that your data structure is an array containing objects, where each object has date strings as keys and arrays of time strings as values. To access the time arrays, you need to:

  1. Access the object in the array: times[0]
  2. Access the time array using the date key: times[0]['2025-03-10']

For more complex operations, you can use JavaScript's array methods and object manipulation functions as demonstrated above.

Sign in to save your work and access it from anywhere