从json

时间:2016-04-19 12:09:56

标签: javascript arrays json underscore.js

我知道这应该很容易,但我根本无法让这件事工作。我有一个具有以下结构的对象:

"name": "Machine 1",
"categories": [
  {
    "name": "Planned",
    "days": [
      {
        "id": 0,
        "date": "2015-09-14T00:00:00",
        "time": 768
      },
      {
        "id": 0,
        "date": "2015-09-15T00:00:00",
        "time": 1100
      },
      {
        "id": 0,
        "date": "2015-09-16T00:00:00",
        "time": 356
      }
    ]
  },
  {
    "name": "Item 1",
    "days": [
      {
        "id": 0,
        "date": "2015-09-14T00:00:00",
        "time": 1323
      },
      {
        "id": 0,
        "date": "2015-09-15T00:00:00",
        "time": 1475
      },
      {
        "id": 0,
        "date": "2015-09-16T00:00:00",
        "time": 668
      }
    ]
  },

因此,如果我想在结构树中显示它,返回的对象将如下所示

  • 计算机的数组
    • 每台计算机都有类别的数组
      • 每个类别都有
      • 的列表

我正在尝试做的而不是我当前的方法(手动迭代)

            angular.forEach(machine.categories, function (category, index) {
                angular.forEach(category.days, function (day, index) {
                    newData.labels.push(day.date);
                });
            });

是使用已经存在的库(根据我的研究,underscore.js应该是完全适合的)并正确地做(我正在努力学习,如何使用它)。

所以我想要实现的是获取日期格式的唯一日期列表。所以我生成的对象看起来像这样:

var result = ["2015-09-14", "2015-09-15", "2015-09-16"](这个会更好)

有没有办法如何使用库(意味着没有手动迭代)?

2 个答案:

答案 0 :(得分:2)

您可以将Set用于唯一值

var data = { "name": "Machine 1", "categories": [{ "name": "Planned", "days": [{ "id": 0, "date": "2015-09-14T00:00:00", "time": 768 }, { "id": 0, "date": "2015-09-15T00:00:00", "time": 1100 }, { "id": 0, "date": "2015-09-16T00:00:00", "time": 356 }] }, { "name": "Item 1", "days": [{ "id": 0, "date": "2015-09-14T00:00:00", "time": 1323 }, { "id": 0, "date": "2015-09-15T00:00:00", "time": 1475 }, { "id": 0, "date": "2015-09-16T00:00:00", "time": 668 }] }] }; 

var set = new Set();

data.categories.forEach(e => e.days.forEach(e => set.add(e.date)));

document.write('<pre>' + JSON.stringify(Array.from(set)) + '</pre>');

答案 1 :(得分:1)

使用下划线(比特详细,假设您在名为data的变量中解析了JSON):

var result = _.uniq(
               _.flatten(
                 _.map(data.categories, function(category) {
                   return _.map(_.pluck(category.days, 'date'), function(date) {
                     return date.replace(/T\d+:\d+:\d+$/, '');
                });
             })));