获取JSON字符串中的所有键值

时间:2017-01-16 20:45:22

标签: angularjs json

我有一个JSON字符串化变量,其中包含一些具有以下格式的日期:

var labs = {
    "2016-01-07":[{
        "date":"2016-01-07T12:45:00.000Z",
        "duration":120,
        "location":"ExampleLocation"
    }],
    "2017-01-05":[{
        "date": "2017-01-05T14:45:00.000Z",
        "duration": 120,
        "location": "ExampleLocation"
      },{
        "date": "2017-01-05T14:45:00.000Z",
        "duration": 120,
        "location": "ExampleLocation"
     }];
}

现在我希望这些日期写在一个有角度的材料日历中。这是通过以下代码完成的:

$scope.setDayContent = function(date) {
        var key = [date.getFullYear(), numFmt(date.getMonth()+1),    numFmt(date.getDate())].join("-");
        var data = (labs[key] || [{ date: ""}])[0].date.slice(11, 16);
        $scope.dayContent = data; //Returns the time and prints it into the calendar cell

这仅适用于每天的第一个对象,因此“2017-01-05”的第二个日期不会打印出来。如何访问所有值并打印相应日历单元格中的每个日期? 我已经记录(labs[key] || [{ date: ""}])[1],但未定义。

1 个答案:

答案 0 :(得分:-1)

首先,您的labs变量无效。它应该是:

var labs = {
    "2016-01-07":[{
        "date":"2016-01-07T12:45:00.000Z",
        "duration":120,
        "location":"ExampleLocation"
    }],
    "2017-01-05":[{
        "date": "2017-01-05T14:45:00.000Z",
        "duration": 120,
        "location": "ExampleLocation"
      }, {
        "date": "2017-01-05T14:45:00.000Z",
        "duration": 120,
        "location": "ExampleLocation"
     }]
};

接下来,如果您尝试为给定日期分配实验室的条目值,或者您尝试分配整个匹配的实验室条目,我不确定代码。如果您只想要数据,请尝试:

$scope.setDayContent = function(date) {
    var key = [date.getFullYear(), numFmt(date.getMonth()+1), numFmt(date.getDate()+1)].join("-");
    var data = labs[key] || [];
    $scope.dayContent = data; //Returns the time and prints it into the calendar cell
};

如果您想要分配整个条目:

$scope.setDayContent = function(date) {
    var key = [date.getFullYear(), numFmt(date.getMonth()+1), numFmt(date.getDate()+1)].join("-");
    var data = {};
    data[date] = labs[key] || [];
    $scope.dayContent = data; //Returns the time and prints it into the calendar cell
};

另外,我假设numFmt具有以下功能:

var numFmt = function(num) {
  if (num < 10) return '0' + num;
  return num.toString();
};

我希望这会有所帮助:)