Search code examples
javascriptarraysjavascript-objects

How do I dynamically change a key in a for loop


I want to be able to change the key in a for loop, it's hard to explain what I need so I made a demo based on the https://www.w3schools.com/js/tryit.asp?filename=tryjs_loop_for play ground.

I need to be able to swap the keys depending on logic because the array data keys will alter depending on the json feed therefore it won't be possible to hard code the keys.

Thanks 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>

Solution

  • You use it like this.

    text += cars[i][keyToChoose] + "<br>";
    

    now it depends on the value of the variable keyToChoose.