0

An object with an array of objects, and a function that returns all the names of each object in the array. This works.

 var persArr = {friends:[
     {name: "Adam", age: 37},
     {name: "Ben", age: 36},
     {name: "Chris", age: 46}],

     getFriend:function(){
         return this.friends.map(function(friend){
           return friend.name;
          }).join(', ').slice();
     }};

   var names = persArr.getFriend();

   console.log(names);

How can I return a name and age property of an object, based on search criteria?

   example: {name:"Chris", age:46}, 
            {name:"Ben",age: "36"} 

      perArr.getFriend("Chris");
Ronnie Headen
  • 289
  • 1
  • 13

3 Answers3

0

Just change your return function to return an object. Something like:

     getFriend:function(name){
         return this.friends.filter(function(friend){
          if(friend.name===name){
           return {name:friend.name, age:friend.age};}
          });
     }};

   var nameAge = persArr.getFriend('Adam');

   console.log(nameAge);
Nishanth Matha
  • 5,993
  • 2
  • 19
  • 28
0

Could change your function to use filter() instead of map:

 getFriend:function(name){
    var match = this.friends.filter(function(friend){
       return friend.name === name;
    });
     return match.length ? match[0] : false;
 }};
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Thank you! This is exactly what i wanted, except the age. I knew how to do it iterating through the array. My mind was just fuzzy thinking how to do it functionally. Also im new at this, just learning. thanks again. – Ronnie Headen Oct 09 '15 at 01:16
0

You can iterate over the list and check if the name matches your search parameter. If it matches return the actual object. In case it doesn't find anything return undefined.

getFriend: function(name) {
    for (var i = 0; i < friends.length; i++) {
        if (friends[i].name == name) {
            return friends[i];
        }
    }
    return undefined;
}