【问题标题】:Angular forEach over Mixed JSON Nests混合 JSON 嵌套的 Angular forEach
【发布时间】:2016-02-16 08:56:36
【问题描述】:

我发现重新定义返回信息以使其适合 ng-repeat 在视图中对其进行迭代非常困难。

我有两个视图,一个是我希望年月包含国家/地区的索引(可能是 1+ 或无),然后在每个国家/地区内我想要每个事件的名称(再次可能是 1+ 或无)。第二个视图我只想传递事件详细信息,并将通过传递事件索引号来调用这些详细信息,以返回所有事件详细信息(名称、mname、net)。

数据:

{
months: [
  {
  index: 201602,
  year: "2016",
  mon: "February",
  country1: [
  {
    index: 12345678,
    l: [
      {
      name: "Test1",
      mname: "Test 1",
      net: "February 10, 2016 11:39:00 UTC",
      }
    ]
    },
    {
    index: 23456789,
    l: [
      {
      name: "Test2",
      mname: "Test 2",
      net: "February 10, 2016 11:39:00 UTC",
      }
    ]
    }
  ],
  country2: [ ]
},
{
index: 201603,
year: "2016",
mon: "March",
country1: [
{
    index: 546547657654,
    l: [
      {
      name: "Test1",
      mname: "Test 1",
      net: "March 10, 2016 11:39:00 UTC",
      }
    ]
}
],
country2: []
},
{
index: 201604,
year: "2016",
mon: "April",
country1: [ ],
country2: [
{
    index: 78676756,
    l: [
      {
      name: "Test1",
      mname: "Test 1",
      net: "April10, 2016 11:39:00 UTC",
      }
    ]
}
]
}
]
}

【问题讨论】:

  • 那么你的问题是什么?是因为某种原因你不能对你的数组进行 ng-repeat 吗?
  • 是的,我无法遍历数组,我相信这是由于角度的限制,我需要在将数组传递给视图之前以某种方式重新定义我需要的级别。

标签: javascript angularjs json foreach


【解决方案1】:

为了让 ng-repeat 工作,您必须在另一个数组中提取国家数据(以某种方式转换初始数据)。

如果这些 country 字段具有一致的命名(例如每个字段上的“国家”中缀),您可以将它们提取到自己的数组中并使用 ng-repeat 对其进行迭代。

这是可行的解决方案。它假定国家/地区数组的名称中都包含“国家”一词:

function MyCtrl($scope) {
    $scope.countriesData = prepData(sampleData);

    function prepData(data) {
      return data.months.map(function(yearMonth) {
        var transformed = { yearMonth: yearMonth, countries: [] };
        for (var key in yearMonth) {
            if (key.indexOf('country') != -1) {
                transformed.countries.push(yearMonth[key]);
            }
        }
        return transformed;
      });
    }
}

var sampleData = {
    months: {
         //...
    }
}

该解决方案获取您提供的数据并将其转换为一组条目,如下所示:{ yearMonth: yearMonth, countries: [] };

你只需要像这样渲染它们:

<div ng-controller="MyCtrl">
<ul>
  <li ng-repeat="entry in countriesData">
    ym-id: {{entry.yearMonth.index}}
    <ul>
      <li ng-repeat="country in entry.countries">
        <ul>
          <li ng-repeat="event in country">
            event-id: {{event.index}}
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>
</div>

你可以在这里查看小提琴:http://jsfiddle.net/tvy4jbvs/

【讨论】:

    猜你喜欢
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 2017-10-30
    • 2017-02-27
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多