I wrote this code example to know the index position of an element that has a specific value in "Name". My variable data contains a list of those elements.
var data = {"Attributes":[
{"Name":"bedrooms","Value":"4"},
{"Name":"bathrooms","Value":"2"},
{"Name":"property_type","Value":"House"},
{"Name":"rateable_value","Value":"$780,000"},
{"Name":"price","Value":"Price by negotiation"},
{"Name":"location","Value":"13"},
{"Name":"district","Value":"Queenstown-Lakes"},
{"Name":"suburb","Value":"Lower Shotover"},
{"Name":"region","Value":"Otago"},
{"Name":"floor_area","Value":"254m²"},
{"Name":"land_area","Value":"1690m²"},
{"Name":"property_id","Value":"CBM959"},
{"Name":"in_the_area","Value":"playground"},
{"Name":"parking","Value":"Large double garage"}
]}
find_index = function(list, str){
list.each(function(index, value){
console.log("Comparing "+value.Name+" with "+str);
if(value.Name == str){
return index;
}
});
};
console.log(find_index($(data.Attributes), "bedrooms"))
When I execute this code, it prints in the log all the comparisons and then return "undefined". What I was expecting is to stop iterations when comparison succeeded, and return 0, which is the position of the element with name "bedrooms".
What is happening here? and how can I solve it?
returnstatement returns from the internal, anonymous function, not thefind_indexfunction.