TechTurtle
TechTurtle

Reputation: 3167

Javascript / AngularJS object selection based on expression as key

I have a javacript object (basically, data coming from webapi call) in below format:

    $scope.Muncipalties = {
    "2290_BR1": "ABBOTTSTOWN",
    "2290_BR2": "ARENDTSVILLE",
    "2290_BR3": "BENDERSVILLE",
    "2290_TS01": "BERWICK TWP",
    "2290_BR4": "BIGLERVILLE",
    "2290_BR5": "BONNEAUVILLE",
    "2290_TS02": "BUTLER TWP",
    "2290_BR6": "CARROLL VALLEY",
    "2290_TS3": "CONEWAGO TWP",
    "2291_TS4": "CUMBERLAND TWP",
    "2291_BR7": "EAST BERLIN",
    "2291_BR8": "FAIRFIELD",
    "2291_TS5": "FRANKLIN TWP",
    "2291_TS6": "FREEDOM TWP"};

Now, I need to create another object from above one, however, it should be filtered by partial key value. i.e. say key is 2290 then only those records should be copied which has key as "2290_". If the key is 2291 then only last 5 records should be copied.

Is there any way in AngulaJS filter to do this?

Plunker is here : https://plnkr.co/edit/OmKHwF1fx1tUVVXYtogp?p=preview

Upvotes: 0

Views: 34

Answers (2)

GeckoTang
GeckoTang

Reputation: 2785

How about the following code?

JS:

$scope.filterId = function(id, items) {
    var result = {};
    angular.forEach(items, function(value, key) {
      if ( key.match(id)  ) {
        result[key] = value;
      }
    });
    return result;
};

HTML:

<div ng-repeat="(k,v) in filterId(2290, Muncipalties)">
  {{v}}
</div>

Upvotes: 0

omarjmh
omarjmh

Reputation: 13896

No need for angular here, thats not an array its an object, to make another object do this:

JsBin example

Here you go:

var obj = {};

for (var prop in m) {
  if (prop.indexOf('2290') > -1) {
    obj[prop] = m[prop];
  }
}

Upvotes: 2

Related Questions