I am looking to dynamically change the key in a for loop. To better explain my needs, I have created a demo using the playground from this link.
My requirement is to be able to switch keys based on certain logic, as the keys in the array data may vary depending on the JSON feed. Therefore, hard coding the keys is not feasible.
Thank you in advance.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>
<p id="demo"></p>
<script>
var cars = [{"name":"BMW", "colour":"blue"}, {"name":"Volvo",
"colour":"green"}, {"name":"Saab", "colour":"pink"}, {"name":"Ford",
"colour":"grey"}, {"name":"Fiat", "colour":"yellow"}, {"name":"Audi",
"colour":"silver"}];
var text = "";
var i;
for (i = 0; i < cars.length; i++) {
var keyToChoose = "name"; /// or I could choose "colour"
text += cars[i][keyToChoose] + "<br>"; /// how do I dynamically change 'keyToChoose'?
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>