You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript遍历数组及重构openingHours结构技术求助

Solution for Traversing and Sorting Dynamic dayNoX Keys in openingHours

Got it, let's fix this problem step by step. First, let's break down why your original code isn't working: when you write el.dayNo+index, you're just concatenating the string "dayNo" with the index number (like "dayNo0"), not actually accessing the property named dayNo1 (or dayNo2, etc.) on the element. To access dynamic property names, you need bracket notation—but even that's not the most reliable here, especially if the keys aren't perfectly aligned with the array index.

Here's a robust approach to handle any structure where you need to grab all keys ending with numbers (specifically dayNoX), sort them by their numeric suffix, and extract their values:

Step-by-Step Implementation

  1. Parse the JSON string into a JavaScript array first—you already know this part, but let's start with that:

    const parsedHours = JSON.parse(openingHours);
    
  2. For each element in the parsed array, extract all keys that match the dayNoX pattern, sort them by the numeric part, then get their values.

Here's the full working code:

// Example input (replace with your actual openingHours string)
const openingHours = '[{"dayNo1":"08:00 to 04:00","dayNo3":"09:00 to 18:00","randomProp":"ignore"},{"dayNo2":"10:00 to 19:00","dayNo1":"07:00 to 16:00"}]';

const parsedHours = JSON.parse(openingHours);

const processedHours = parsedHours.map(el => {
  // 1. Get all keys that start with "dayNo" followed by numbers
  const dayKeys = Object.keys(el).filter(key => /^dayNo\d+$/.test(key));
  
  // 2. Sort the keys by their numeric suffix (so dayNo1 comes before dayNo2, etc.)
  const sortedDayKeys = dayKeys.sort((keyA, keyB) => {
    // Extract the number from each key
    const numA = parseInt(keyA.replace('dayNo', ''), 10);
    const numB = parseInt(keyB.replace('dayNo', ''), 10);
    // Sort numerically (ascending order)
    return numA - numB;
  });
  
  // 3. Extract the values in the sorted order
  return sortedDayKeys.map(key => el[key]);
  
  // Optional: If you want to keep key-value pairs instead of just values, use this:
  // return sortedDayKeys.reduce((acc, key) => ({ ...acc, [key]: el[key] }), {});
});

console.log(processedHours);
// Output:
// [
//   ["08:00 to 04:00", "09:00 to 18:00"],
//   ["07:00 to 16:00", "10:00 to 19:00"]
// ]

Key Details Explained

  • Object.keys(el).filter(...): This grabs every property name from the element, then filters down to only those that match our regex pattern /^dayNo\d+$/—this ensures we only get keys like dayNo1, dayNo2, etc., and ignore any unrelated properties.
  • Sorting by numeric suffix: The sort function extracts the number from each key (by removing "dayNo"), converts it to an integer, then sorts numerically. This avoids string sorting issues (like dayNo10 coming before dayNo2 if we sorted the strings directly).
  • Flexible structure: Unlike your original approach that relied on array index matching the dayNo number, this works even if keys are missing, out of order, or not consecutive (like dayNo1 and dayNo3 with no dayNo2).

Why Your Original Code Failed

Your line let workingHours = el.dayNo+index; was creating a string like "dayNo0" (when index is 0), but to access the property dayNo1, you'd need to use bracket notation: el[dayNo${index + 1}] (since index starts at 0). But this approach is fragile—if the keys don't perfectly match the array index +1, it'll break. The filter-and-sort method above is much more reliable for non-standard structures.

内容的提问来源于stack exchange,提问作者Folky.H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:36:15