【问题标题】:Iterating over nested json array with angular使用角度迭代嵌套的json数组
【发布时间】:2015-07-03 20:46:49
【问题描述】:

我正在使用 Angular 从 Web 服务中获取数据,数据是 JSON 格式:

    {
    "items": [{
        "id": 2,
        "catId": 1,
        "content": "ddddddddddddddddd",
        "type": 0,
        "comments": [{
            "id": 0,
            "postId": 0,
            "userId": 0,
            "content": "nincompoop",
            "ptime": "2015"
        }, {
            "id": 0,
            "postId": 0,
            "userId": 0,
            "content": "lol",
            "ptime": "2015"
        }],
        "Likes": []
    }, {
        "id": -1,
        "catId": 1,
        "content": "first post",
        "type": 0,
        "comments": [{
            "id": 1,
            "postId": 0,
            "userId": 0,
            "content": "first Comment",
            "ptime": "2015"
        }],
        "Likes": [{
            "id": 1,
            "name": "Rawhi"
        }]
    }]
}

用户 ID 也存储在 javascript 参数中,如何遍历每个帖子的“item.likes”并确定用户 ID 是否存在?谢谢你

【问题讨论】:

  • 使用javascript 或者你想在template 中使用ng-Repeat

标签: json angularjs


【解决方案1】:

假设您的 JSON 在名为 rawhi 的变量中:

angular.forEach(rawhi, function (item, key){
    angular.forEach(item, function(comment, index){
        comment.userId //you can check if this exists
        //iterate over the likes array:
        angular.forEach(comment.Likes, function (like, i){
            like //you can do whatever you want to do with this
        });
    });
});

基本上,您可以使用嵌套的 foreach 循环来遍历 JSON 中的数组。

【讨论】:

    【解决方案2】:

    forEach.item.Likes(function(prop){ alert(prop) });

    或者在您的角度控制器视图中,您可以使用 ngRepeat 指令来遍历它,但是您需要在其中任何一个工作之前清理该对象。还要从代码中删除诅咒词!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多