Reputation: 521
If I enter the array identifiers manually it will work, however using the parameters in the function it won't work. I know where the problem is, but not what I can replace ".key" with, so that it'll use the parameters value.
var stuff = [
{ "name": "Alex", "food": "Pizza"},
{ "name": "Karl", "food": "Lasagne"},
{ "name": "Franz", "food": "Potato salad"}
]
function getSpecificValue(key, value, getkey, arr) {
for (var i=arr.length;i--;) {
if (arr[i].key == value) { //this should use the parameter "key" ("name")
return arr[i].getkey; //this should use the parameter "getkey" ("food")
}
}
}
alert( getSpecificValue('name', 'Alex', 'food', stuff) ); //alert "Pizza"
Upvotes: 0
Views: 303
Reputation: 64657
You can always access object properties using "bracket" or "array" notation:
for (var i=arr.length;i--;) {
if (arr[i][key] == value) { //this should use the parameter "key" ("name")
return arr[i][getkey]; //this should use the parameter "getkey" ("food")
}
}
Upvotes: 1