【问题标题】:Angularjs: How do I ng-repeat through an array of objects with a field that is also an array?Angularjs:我如何重复一个对象数组,其中一个字段也是一个数组?
【发布时间】:2018-06-05 19:41:02
【问题描述】:

我有一个如下所示的数组:

0: {ID: null, 
 name: "test", 
 city: "Austin", 
 UserColors: [{color: "blue"},{hobby:"beach"} ... ]}
 }...

我正在尝试对初始数组进行 ng-repeat,但是一旦我尝试遍历列表,我什么也看不到,这是 html/angular

      <tr ng-repeat="c in vm.people">
                        <td>{{c.name}}</td>
                        <td>{{c.city}}</td>   

                        <td ng-repeat="uc in c.UserColors">
                            <td>{{uc.color}}</td>
                        </td>

                    </tr>

我不确定出了什么问题,非常感谢您的帮助,在此先感谢您。

【问题讨论】:

  • list 是循环变量的一个好名字。选择别的东西
  • 'list' 只是我在此示例中发布的随机变量@NiVeR
  • 你能把你的json的完整结构贴出来吗,外面的好像不是数组
  • 1.尝试在 td 中省略 td。 2. 你的 UserColors 数组似乎只有一个具有颜色属性的对象,另一个是爱好 - 所以你会在那里得到未定义

标签: javascript arrays angularjs angularjs-ng-repeat


【解决方案1】:

我将使用自定义过滤器处理该字段:

<td ng-repeat-start="(key, value) in c.UserColors  | reduce">
      <b>{{key}}</b>
</td>
<td ng-repeat-end>
      {{value}}
</td>

过滤器:

app.filter("reduce",function() {
  return function(items) {
    var x = items.map(o => Object.entries(o));
    var x2 = x.reduce(((a,x) => (a.concat(x))), []);
    var x3 = x2.reduce(((o,x) => (o[x[0]]=x[1],o)), {});
    return x3;
  }
})

The DEMO

angular.module("app",[])
.controller("ctrl",function(){
  var vm = this;
  vm.people = {
    0: {ID: null, 
        name: "test", 
        city: "Austin", 
         UserColors: [{color: "blue"},{hobby:"beach"}]
      },
    1: {ID: null, 
        name: "best", 
        city: "Boston", 
         UserColors: [{colorx: "red"},{shirt:"black"}]
      },
    2: {ID: null, 
        name: "rest", 
        city: "Paris", 
         UserColors: [{colory: "yel"},{fruit:"peach"}]
      },
  }
})
.filter("reduce",function() {
  return function(items) {
    var x = items.map(o => Object.entries(o));
    var x2 = x.reduce(((a,x) => (a.concat(x))), []);
    var x3 = x2.reduce(((o,x) => (o[x[0]]=x[1],o)), {});
    return x3;//items;
  }
})
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app" ng-controller="ctrl as vm">
    <h3>Table</h3>
    <table>
      <tr ng-repeat="c in vm.people">
        <td>{{c.name}}</td>
        <td>{{c.city}}</td>   

        <td ng-repeat-start="(key, value) in c.UserColors  | reduce">
              <b>{{key}}</b>
        </td>
        <td ng-repeat-end>
              {{value}}
        </td>
        
      </tr>
    </table>
  </body>

【讨论】:

    猜你喜欢
    • 2021-10-02
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多