简体   繁体   中英

Pull value from JSON key value pair using AngularJS

Is there a nice way in Angular's ngRepeat to pull a value out of a JSON Array depending on its key. I working with the following JSON structure and would like to output the associated value of "Name 2" for each object.

{
  "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"
        }
      ]
    }
  ]
}

try like this

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

Here is an example. It will print the Value for "Name 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM