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"
asked Aug 4, 2014 at 20:55
Kallewallex
5191 gold badge6 silver badges24 bronze badges
1 Answer 1
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")
}
}
answered Aug 4, 2014 at 21:01
dave
65.1k6 gold badges81 silver badges98 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Kallewallex
Thanks :) @elclanrs comment already provided me with what I was looking for. But I'll accept your answer for anyone who may stumble upon this page.
lang-js
if (arr[i][key] == value) { return arr[i][getkey]; }Thanks, I would accept your answer, if it wouldn't be a comment ;)