【问题标题】:How to order this JSON response by AM/PM time property?如何按 AM/PM 时间属性订购此 JSON 响应?
【发布时间】:2020-06-28 07:01:44
【问题描述】:

我有一个如下所示的 JSON 对象,

{
10-AM: {
...
},
10-PM: {
....
},
11-AM: {
....
},
11-PM: {
....
}
}

这里的要求是我需要在 12 小时内订购并制作,

{
10-AM: {
...
},
11-AM: {
....
},
10-PM: {
....
},
11-PM: {
....
}
}

因为我尝试了不同的不同逻辑,但无法正确处理。有没有办法按顺序得到结果?

【问题讨论】:

  • 这是一个对象,不能保证顺序,用数组代替。

标签: javascript arrays json sorting


【解决方案1】:

试试这个功能:

const times = {
  "10-AM": { time: "its 10 am" },
  "07-PM": { time: "its 7 pm" },
  "11-AM": { time: "its 11 am" },
  "09-PM": { time: "its 9 pm" },
  "12-PM": { time: "its 12 pm"  },
  "10-PM": { time: "its 10 pm" },
  "01-AM": { time: "its 1 am" },
  "11-PM": { time: "its 11 pm"  }
}

const sortTimes = (times) => {
  const keys = Object.keys(times)
  const am = keys.filter(key => key.indexOf("AM") > 0)
  const pm = keys.filter(key => key.indexOf("PM") > 0)
  const sorted = [...am.sort(), ...pm.sort()]
  const sortedObject = {}
  for (let i = 0; i < sorted.length; i++ ) {
    sortedObject[sorted[i]] = times[sorted[i]]
  }

  return sortedObject
}

console.log(sortTimes(times))

【讨论】:

    【解决方案2】:

    正如@gorak 所说的非常正确,您不能保证对象中属性的顺序。所以你应该瞄准一个对象数组。在 12 小时制中,“12 p.m.”的时间存在异常:像下午 12:15 这样的时间。米。相当于 24 小时制的 00:15h,并在一天的第一个小时标记时间。因此,如果您的每小时间隔指的是给定时间之后的小时,您需要为此做出规定:i。例如:12 点。米。变为“凌晨 0 点”。没有人会这样写,但这是任何算法都可以毫无问题地对其进行排序的方式。

    const times = {
      "10-AM": { time: "it's 10 am" },
      "07-PM": { time: "it's 7 pm" },
      "11-AM": { time: "it's 11 am" },
      "09-PM": { time: "it's 9 pm" },
      "12-PM": { time: "it's 12 pm"  },
      "10-PM": { time: "it's 10 pm" },
      "01-AM": { time: "it's 1 am" },
      "11-PM": { time: "it's 11 pm"  }
    }
    
    const keys=Object.keys(times).map(k=>{
      let srt=k.substr(3)+k.substr(0,2)
      if (srt=="PM12") srt="AM00";
      return {k,srt}; })
    .sort((a,b)=>a.srt.localeCompare(b.srt)).map(k=>k.k);  
    // now we have the keys in an ordered array:
    console.log(keys)
    // and can list the times object with it
    keys.forEach(k=>console.log(k+':'+times[k].time))
    // or you can generate a sorted array of objects:
    let sorted=keys.map(k=>times[k]);
    console.log(sorted);

    【讨论】:

      猜你喜欢
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 2021-10-29
      • 2023-03-16
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多