如何从对象中获取JSON数组

时间:2016-11-22 22:37:13

标签: javascript angularjs json parsing

我是JSON的新手,我正在尝试提取名为“steps”的数组,以及此JSON获取请求结果中的字符串“step”:angularJS:

Payload

Payload.data

但是,我无法通过尝试以下方法获取此信息(提供未定义或错误):

payload.data.steps
payload.data.steps[0].step
payload.data[0].steps

任何指导都将不胜感激!

解决 谢谢大家的深思熟虑和全面的答案。我犯了一些错误,包括具有异步http.get结果的错误。

为了将来参考,在我的services.js中,我以这种方式将get请求传递给我的控制器:

var recipes = payload.data[0].steps;

并且在我的controller.js中我确保让它等待回调(而不是接收承诺),然后将其保存到范围内:

RecipeDetails.getInstructions($scope.details.id).then(function(InstructionPayload){
      $scope.instructions = InstructionPayload;

并在我的HTML页面中单独显示步骤:

//Steps:
<div ng-repeat="list in instructions track by $index">
<p>{{ list.step }}</p>

2 个答案:

答案 0 :(得分:0)

在这里快速了解一下,希望它有所帮助。如果需要,我可以随时更新。

&#13;
&#13;
function exampleController($scope) {
  $scope.example = [{
    name: "",
    steps: [{
      equipment: [],
      ingredients: [],
      number: 1,
      step: 'Blah'
    }]
  }, {
    name: "",
    steps: [{
      equipment: [],
      ingredients: [],
      number: 2,
      step: 'Bibbidi'
    }]
  }, {
    name: "",
    steps: [{
      equipment: [],
      ingredients: [],
      number: 3,
      step: 'Bobbidi'
    }]
  }, {
    name: "",
    steps: [{
      equipment: [],
      ingredients: [],
      number: 4,
      step: 'Boo'
    }]
  }];

  function extractSteps() {
    $scope.stepArray = [];
    $scope.example.forEach(function(step) {
      if (step.steps && Array.isArray(step.steps)) {
        step.steps.forEach(function(value, index) {
          if (value && value.step) {
            $scope.stepArray.push({
              'step': value.step
            })
          }
        });
      }
    });
  }
  extractSteps();
}

angular
  .module('app', [])
  .controller('exampleController', exampleController);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container-fluid" ng-app="app">
  <div class="container" ng-controller="exampleController">
    <div class="row" ng-repeat="(key, value) in example" ng-bind="value.steps[0].step">
    </div>
    <div class="row" ng-repeat="value in stepArray">
      <pre>{{value | json}}</pre>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您在应用程序中有下划线或lodash,您可以将一些内容链接在一起,如下所示:

_.chain(obj.data) // wrap the data so we can chain transformations
  .map('steps') // gather all the steps arrays from the main array
  .flatten() // smash them into a single array
  .map('step') // grab all the step properties from those
  .value() // return the value -> ["Blah", "Bibbidi", "Bobbidi", "Boo"] from alphapilgrim's example data