-2

where will the return put the friend[i]?

where will the return put the friend[i]?

where will the return put the friend[i]?

var friends = {
    steve: {
        firstName: "Steve",
        lastName: "Jobs",
        number: "(831)524-2213",
        address: ["531 Recht St.","Hollister","CA","95037"] 
    },
    bill: {
        firstName: "Bill",
        lastName: "Gates",
        number: "(831)524-0349",
        address: ["310 E Dunne Ave", "Morgan Hill", "CA","95037"]
    }
};
var search = function(name){
    for (var i=0;i<friends;i++){
        if (friends[i].firstName === name) {
            console.log(friends[i]);
            return friends[i];
        } 
    }
};

1 Answers1

1

The problem is friends is an object not an array so your loop is wrong

If you want to keep friends as an object itself, then you need to iterate over the properties of that object

var search = function (name) {
    for (var key in friends) {
        if (friends.hasOwnProperty(key) && friends[key].firstName === name) {
            console.log(friends[key]);
            return friends[key];
        }
    }
};

Demo: Fiddle


Or use an array instead

var friends = [{
    firstName: "Steve",
    lastName: "Jobs",
    number: "(831)524-2213",
    address: ["531 Recht St.", "Hollister", "CA", "95037"]
}, {
    firstName: "Bill",
    lastName: "Gates",
    number: "(831)524-0349",
    address: ["310 E Dunne Ave", "Morgan Hill", "CA", "95037"]
}];
var search = function (name) {
    for (var i = 0; i < friends.length; i++) {
        if (friends[i].firstName === name) {
            console.log(friends[i]);
            return friends[i];
        }
    }
};

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • they says that for .. in loop is a bad practice... they say better use for(..;..;..) than for .. in . http://stackoverflow.com/questions/2265167/why-is-forvar-item-in-list-with-arrays-considered-bad-practice-in-javascript is that a true? – jubiluk babawakis May 04 '15 at 05:29
  • @jubilukbabawakis look at the title `Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?` - it is related to handling arrays, in your case it is not an array... – Arun P Johny May 04 '15 at 05:30
  • ok ... I know now ... but where will the return put the return friends[key] ? – jubiluk babawakis May 04 '15 at 05:36
  • @jubilukbabawakis where you have it is fine... look at the attached fiddle to see it working – Arun P Johny May 04 '15 at 05:39