0

With this associative array, I would like to find a specfic key:

var veggie_prices = new Array();
veggie_prices["serves6"] = 20;
veggie_prices["serves8"] = 25;
veggie_prices["serves10"] = 35;

If I loop through the array, I can find the values with:

var x = veggie_prices[i].value;

but how should the key be found ?

var y = veggie_prices[i].key;

2 Answers 2

4

To directly answer your question, use a for..in loop

var veggie_prices = new Array();
veggie_prices["serves6"] = 20;
veggie_prices["serves8"] = 25;
veggie_prices["serves10"] = 35;
for (var i in veggie_prices) {
  console.log(i); // output: serves6, etc..
}

However, just to be clear, javascript does not have associative arrays. What you have is an object of type array, and you just added several properties to it, in addition to the normal (albeit empty at the moment) index and other native array properties/methods (e.g. .length, .pop(), etc..)

Sign up to request clarification or add additional context in comments.

1 Comment

Just to add context - Currently, this list is using radio button controls for selection on the list. To find the selected radio button with a for loop, I used .checked method and .value to get the value. using .key did not yield the key. Not sure why. Thank you for your answer.
2

Why are you using an array? Can you use an object instead?

var veggie_prices = {};
veggie_prices["serves6"] = 20;
veggie_prices["serves8"] = 25;
veggie_prices["serves10"] = 35;

Object.keys(veggie_prices).forEach((key) => {
  console.log('Key is: ' + key);
  console.log('Value is: ' + veggie_prices[key]);
});

1 Comment

Yes will move to objects. Currently, this list is using radio button controls for selection on the list. To find the selected radio button, I used .checked method and .value to get the value. using .key did not yield the key. Not sure why. Thank you for your answer.

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.