0

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"
2
  • 5
    You're looking for "bracket notation", see here developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Aug 4, 2014 at 20:56
  • 2
    okay, got it if (arr[i][key] == value) { return arr[i][getkey]; }Thanks, I would accept your answer, if it wouldn't be a comment ;) Commented Aug 4, 2014 at 21:01

1 Answer 1

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")
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.