Search code examples
angularjsangularjs-scopeangularjs-controllerangularjs-filter

AngularJS multiple Scope needed for Autocomplete


I have an array structure like this.

[
  {
    "id": "1",
    "name": "John",
    "city": "NY"
  },
  {
    "id": "2",
    "name": "Gerold",
    "city": "LA"
  },
  {
    "id": "3",
    "name": "Stuart",
    "city": "Boston"
  }  
]

I need $scope like below for my autocomplete search.

$scope.name=["john","Gerold","Stuart"];
$scope.city=["NY","LA","Boston"];

can anyone help to get this using angularjs controller. Thanks in Advance.!


Solution

  • You can use MAP..

    $scope.YourBigArray = [{
      "id": "1",
      "name": "John",
      "city": "NY"
    }, {
      "id": "2",
      "name": "Gerold",
      "city": "LA"
    }, {
      "id": "3",
      "name": "Stuart",
      "city": "Boston"
    }];
    
    $scope.names = $scope.YourBigArray.map(function(object) {
      return object.name;
    });
    $scope.cities = $scope.YourBigArray.map(function(object) {
      return object.city;
    });
    

    You can do a filter to use unique things in array of names and cities..

    function filterForDuplicate(things) {
      return things.filter(function(item, pos) {
        return things.indexOf(item) === pos;
      });
    }