ChrisGeo
ChrisGeo

Reputation: 3907

AngularJS Map one object to another

I want to map a $scope.filters object to a var criteria on the condition if the original fields are null or not.

So lets say I have:

$scope.filters = {
    name: 'myName'
    lastName: null,
    age: null,
}

I want my var criteria to be mapped to non null fields like this:

var criteria = {
    name: 'myName';
}

So I have tried like this:

var criteria = {};

angular.forEach($scope.filters, function (value, key, obj) {
        if (value != null) {
            this.push(obj)
        }
}, criteria);

But I guess I'm missing something.

Upvotes: 0

Views: 4361

Answers (2)

Fahad Khan
Fahad Khan

Reputation: 1635

You should do it like this,

$scope.filters = {
  name: 'myName'
  lastName: null,
  age: null,
 }

var criteria = []; //array, you were using object
    angular.forEach($scope.filters, function(value, key) {
      if (value != null) {
            this.push(key + ': ' + value);
        }

    }, criteria);  

expect(criteria).toEqual(['name: myName']);

Hope it helps.

Upvotes: 1

Sycomor
Sycomor

Reputation: 1272

criteria is an object, not an array, so you can't push it. Either make it an array if you want to store separate individual criteria, or replace the push with this[key] = value;

Upvotes: 1

Related Questions