user3125823 user3125823 - 4 months ago 24
Javascript Question

AngularJS forEach iteration

I have this JSON data, which is a return from Elasticsearch search results for an autocomplete query using ES's match_phrase_prefix query:

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


So what I'm trying to do is iterate through this to get the value of "ymme".

My current function in my controller for the autocomplete suggestions is like this:

//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;
});
};


What is happening here is that the suggestions display in the dropdown but the value of "ymme" (the actual suggestion) is not being passed to $scope.autocomplete.suggestions.

I need to iterate through the results and push the value of "ymme" to $scope.autocomplete.sugggestions, I've been looking at angular.forEach but I'm not sure how to implement it since I'm dealing with a key, value pair that is in an object, which is in an object, which is an array, which is in yet another object:

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


Any ideas, suggestions?

UPDATE

//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)">

Answer

You can use map like this:

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

I hope this will help you.

Comments