2

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.

1
  • are you trying to get the output after submit from a page? Commented Nov 17, 2014 at 11:04

2 Answers 2

2

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"}];
Sign up to request clarification or add additional context in comments.

2 Comments

I need them to send over http. I need to save some bandwidth here :). While your answer is working and a correct answer, It would be nice if I can use angularjs inbuilt service like $filter.
This is the correct answer, based on what you asked for the data being sent over http will be EXACTLY the same as what you wanted. If you were to write a filter, it would look almost exactly the same.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.