使用AngularJS从JSON键值对中拉取值

时间:2016-05-08 15:12:13

标签: angularjs json

Angular的ngRepeat中是否有一种很好的方法可以根据其密钥从JSON数组中提取值。我使用以下JSON结构,并希望为每个对象输出相关的“名称2”值。

{
  "Items": [
    {
      ...
      "Attributes": [
        {
          "Name": "Name 1",
          "Value": "123"
        },
        {
          "Name": "Name 2",
          "Value": "456"
        },
        {
          "Name": "Name 3",
          "Value": "789"
        }
      ]
    },
    {
      ...
      "Attributes": [
        {
          "Name": "Name 1",
          "Value": "987"
        },
        {
          "Name": "Name 2",
          "Value": "654"
        },
        {
          "Name": "Name 3",
          "Value": "321"
        }
      ]
    },
    {
      ...
      "Attributes": [
        {
          "Name": "Name 1",
          "Value": "246"
        },
        {
          "Name": "Name 2",
          "Value": "369"
        },
        {
          "Name": "Name 3",
          "Value": "135"
        }
      ]
    }
  ]
}

2 个答案:

答案 0 :(得分:0)

试试这个

 angular.forEach(data.Items,function(value,key){
     angular.forEach(value,function(v){
       if(v.name == "Name 2")
         console.log(v);
     }
  })

答案 1 :(得分:0)

这是一个例子。它将打印"名称2"

<body ng-app="myApp">

  <div ng-controller="myCtrl">
    <div ng-repeat="item in records.Items">
      <div ng-repeat="singleAttribute in item.Attributes">
        <div ng-if="singleAttribute.Name === 'Name 2'">
          {{singleAttribute.Value}}
        </div>
      </div>
    </div>
  </div>

<script>
  var app = angular.module("myApp", []);
  app.controller("myCtrl", function($scope) {
    $scope.records = {
      "Items": [
        {
          "Attributes": [
            {
              "Name": "Name 1",
              "Value": "123"
            },
           {
             "Name": "Name 2",
             "Value": "456"
           },
          {
            "Name": "Name 3",
            "Value": "789"
          }
        ]
      },
      {
        "Attributes": [
          {
            "Name": "Name 1",
            "Value": "987"
          },
          {
            "Name": "Name 2",
            "Value": "654"
          },
          {
            "Name": "Name 3",
            "Value": "321"
          }
        ]
      },
      {

        "Attributes": [
          {
            "Name": "Name 1",
            "Value": "246"
          },
          {
            "Name": "Name 2",
            "Value": "369"
          },
          {
            "Name": "Name 3",
            "Value": "135"
          }
        ]
      }
    ]
  };
});
</script>

</body>