AngularJS forEach迭代

时间:2016-07-14 21:02:57

标签: javascript angularjs

我有这个JSON数据,这是使用ES的match_phrase_prefix查询从Elasticsearch搜索结果返回自动完成查询:

    "hits": {
   "total": 3,
   "max_score": 3.3071127,
   "hits": [
      {
         "_source": {
            "ymme": "bourne supremacy"
         }
      },
      {
         "_source": {
            "ymme": "bourne ultimatum"
         }
      },
      {
         "_source": {
            "ymme": "bourne idendity"
         }
      }

所以我要做的就是迭代这个以获得" ymme"的价值。

我的控制器中我自动完成建议的当前功能如下:

//suggestions
$scope.getSuggestions = function(query) {
$scope.isSearching = true;
return searchService.getSuggestions(query).then(function(es_return){
    var phrases = es_return.hits.hits;
    console.log(phrases);
    if (phrases) {
      return $scope.autocomplete.suggestions = phrases;
      console.log(suggestions)
    }
    else {
      $scope.autocomplete.suggestions = [];
      $scope.noResults = true;
    }
    $scope.isSearching = false;
    },
    function(error) {
      console.log('ERROR: ', error.message);
      $scope.isSearching = false;
    });
  };

这里发生的事情是建议显示在下拉列表中,但是" ymme" (实际建议)未传递给$ scope.autocomplete.suggestions。

我需要遍历结果并推送" ymme"到$ scope.autocomplete.sugggestions,我一直在关注angular.forEach,但我不确定如何实现它,因为我正在处理一个关键的值对object,它位于一个对象中,它是一个数组,它位于另一个对象中:

"hits": {
   "hits": [
      {
         "_source": {
            "ymme": "bourne supremacy"
           }
         }
       ]
     }

任何想法,建议?

更新

//suggestions
$scope.getSuggestions = function(query) {
    $scope.isSearching = true;
    return searchService.getSuggestions(query).then(function(es_return) {
        var phrases = es_return.hits.hits;
        if (phrases) {
            return $scope.autocomplete.suggestions = phrases.map(function(item) {
                return item._source.ymme;
            })
        } else {
            $scope.autocomplete.suggestions = [];
            $scope.noResults = true;
        }
        $scope.isSearching = false;
    }, function(error) {
        console.log('ERROR: ', error.message);
        $scope.isSearching = false;
    });
};

HTML dropwdown

<input type="text" ng-model="searchTerms" class="form-control input-md" placeholder="{{ searchTerms }}" name="q" id="srch-term" uib-typeahead="query as query._source.ymme for query in getSuggestions($viewValue)" typeahead-on-select="search($item)">

2 个答案:

答案 0 :(得分:1)

您可以像这样使用map

return $scope.autocomplete.suggestions = phrases.map(function(item) {
    return item._source.ymme;
});

<强> HTML:

<input type="text" 
     ng-model="searchTerms" class="form-control input-md" 
     placeholder="{{ searchTerms }}" name="q" 
     id="srch-term" 
     <!-- change this -->
     uib-typeahead="query for query in getSuggestions($viewValue)" 
     typeahead-on-select="search($item)">

我希望这会对你有所帮助。

答案 1 :(得分:0)

如果您想使用角度forEach - &gt;

var res = [];
angular.forEach(hits.hits, function(src) {
   res.push(src._source.ymme);    
});