请帮忙,我有一个Angular方法,我试图从一个对象中获取值,并得到一个看起来为“ Monday-Friday:0800-1600”的结果。

$scope.ourHours = {
  services: [{
    title: "Office hours",
    phone: "1-800-123-1234",
    hours: [
      {day:'Monday',open:'0800',close:'1800'},
      {day:'Tuesday',open:'0800',close:'1800'},
      {day:'Wednesday',open:'0800',close:'1800'},
      {day:'Thursday',open:'0800',close:'1800'},
      {day:'Friday',open:'0800',close:'1800'}
    ]
  }]
};

最佳答案

我会跟踪过去的日子,如果时间匹配,将它们分组:



function getHoursText(hours){
    var arr = [], txt = [];

    for(var i=0; i<hours.length; i++){
        if(arr.length &&
           (arr[0].open !== hours[i].open || arr[0].close !== hours[i].close)
          ){
            txt.push(arrayToText(arr));
            arr = [];
        }
        arr.push(hours[i]);
    }

    txt.push(arrayToText(arr));

    return txt.join('\n');

    function arrayToText(arr){
        var str;
        if(!arr.length){ return ""; }
        str = arr[0].day;
        if(arr.length > 1){ str += '-' + arr.pop().day; }
        str += ': ' + arr[0].open + '-' + arr[0].close;
        return str;
    }
}

/*
 * Example usage
 */
var hours = [
      {day:'Monday',open:'0800',close:'1500'},
      {day:'Tuesday',open:'0800',close:'1800'},
      {day:'Wednesday',open:'0800',close:'1800'},
      {day:'Thursday',open:'0800',close:'1800'},
      {day:'Friday',open:'0800',close:'1500'}
    ];

console.log( getHoursText(hours) );

10-08 00:20