Dasun
Dasun

Reputation: 3294

Angularjs: How to filter selected fields from an object array

Lets say I have an object array like this

peoples = [{name:"Joe",age:21,sex:'M'},
{name:"Smith",age:18,sex:'M'},{name:"Sally",age:25,sex:'F'}];

Some of these fields are irrelevant so I need to remove attribute age and sex from all of above objects.

This is the desired output.

 [{name:"Joe"},{name:"Smith"},{name:"Sally"}];

Update: It would be nice if I can use angularjs inbuilt service like $filter.

Upvotes: 2

Views: 1542

Answers (2)

Martin
Martin

Reputation: 604

Well I don't see the need to remove the unnecessary objects since you only access the fields you want. Otherwise you can create a new array from the one you have created chucking out what you don't want.

var peoples = [{name:"Joe",age:21,sex:'M'},{name:"Smith",age:18,sex:'M'},{name:"Sally",age:25,sex:'F'}];
var names = [];
peoples.forEach(function(entry) {
    names.push({name:entry.name});
});
console.log("New Names:",names); //[{name:"Joe"},{name:"Smith"},{name:"Sally"}];

Upvotes: 2

Michael
Michael

Reputation: 3326

Just do:

   for( var i = 0; i < peoples.length; ++i ) {
             delete peoples[i].age;
             delete peoples[i].sex;
   }

delete is the keyword created for this

Upvotes: 1

Related Questions