ES6数组修改:拆分含多个time_in的元素为新项的实现方法
time_in Values in ES6 Hey there! Let's work through this problem together—splitting array elements that have multiple time_in entries into separate rows is a common task, and ES6 has some handy tools to make this clean and straightforward.
First, let’s assume your original array looks something like this (feel free to adjust if your structure is a bit different):
const originalArray = [ { id: 1, name: "Alice", time_in: ["09:00", "13:00"] }, { id: 2, name: "Bob", time_in: ["10:00"] }, { id: 3, name: "Charlie", time_in: ["08:30", "12:30", "17:00"] } ];
The ES6 Approach: Using flatMap
The flatMap method is perfect here—it combines mapping each element with flattening the result in one step, which is exactly what we need for splitting and merging. Here’s the implementation:
const splitArray = originalArray.flatMap(item => { // Check if time_in is an array with multiple values if (Array.isArray(item.time_in) && item.time_in.length > 1) { // Create a new object for each time_in value, keeping other properties intact return item.time_in.map(time => ({ ...item, // Copy all existing properties from the original item time_in: time // Replace the array with a single time value })); } // If no split is needed, return the item wrapped in an array (required for flatMap) return [item]; });
Breakdown of How This Works
flatMaploops through every element in your original array. For each element:- If
time_inis an array with more than one entry, we usemapto generate a new object for each time value. The spread operator (...item) copies all other properties (likeid,name) so we don’t lose any existing data. - If the element only has one
time_invalue, we return it as-is (wrapped in an array soflatMapcan process it correctly).
- If
Example Output
When you log splitArray, you’ll get this nicely split result:
[ { id: 1, name: "Alice", time_in: "09:00" }, { id: 1, name: "Alice", time_in: "13:00" }, { id: 2, name: "Bob", time_in: "10:00" }, { id: 3, name: "Charlie", time_in: "08:30" }, { id: 3, name: "Charlie", time_in: "12:30" }, { id: 3, name: "Charlie", time_in: "17:00" } ]
Handling String-Based time_in Values
If your time_in is a comma-separated string (like "09:00,13:00" instead of an array), just add a quick conversion step:
const splitArrayForStrings = originalArray.flatMap(item => { // Convert string to array if needed, trimming whitespace from each time entry const timeEntries = typeof item.time_in === 'string' ? item.time_in.split(',').map(time => time.trim()) : item.time_in; if (Array.isArray(timeEntries) && timeEntries.length > 1) { return timeEntries.map(time => ({ ...item, time_in: time })); } return [item]; });
This should cover most scenarios—if your array has any unique quirks, feel free to tweak the logic to match your structure!
内容的提问来源于stack exchange,提问作者Geoff

