0

Hopefully this is pretty simple.. example below:

 var myArray = [{color:"red",name:"1"},{color:"blue",name:"2"},{color:"green",name:"3"},{color:orange,name:4},{color:"yellow",name:"5"}];

 for (i=0; i<myArray.length; i++){
      if (myArray[i].color == "red"){
           console.log ("yep");
      }
 }

This of course works fine, but what if I want to exchange "color" with a variable:

 var myArray = [{color:"red",name:"1"},{color:"blue",name:"2"},{color:"green",name:"3"},{color:orange,name:4},{color:"yellow",name:"5"}];

 var c = "color";

 for (i=0; i<myArray.length; i++){
      if (myArray[i].c == "red"){
           console.log ("yep");
      }
 }
Chuck.M
  • 5
  • 2
  • 1
    Possible duplicate of [JavaScript property access: dot notation vs. brackets?](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – ASDFGerte Sep 24 '19 at 18:05

2 Answers2

0

You should use [] notation to access a variable field:

let c = 'color';
for (i = 0; i < myArray.length; i++) {
  if (myArray[i][c] === 'red'){
    console.log('yep');
  }
}

More on the two methods here

Danny Buonocore
  • 3,731
  • 3
  • 24
  • 46
  • 1
    Sigh, I knew that was the right track.. i was trying it with brackets with a dot between them... thanks for the fast response! – Chuck.M Sep 24 '19 at 18:42
0

Then you'll need to use bracket notation instead of dot notation:

var myArray = [{color:"red",name:"1"},{color:"blue",name:"2"},{color:"green",name:"3"},{color:"orange",name:4},{color:"yellow",name:"5"}];

var c = "color";

for (i = 0; i < myArray.length; i++) {
  if (myArray[i][c] == "red") {
    console.log("yep");
  }
}
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • Sorry, absolutely correct answer but missed the correct by one minute :/ Really appreciate it though. – Chuck.M Sep 24 '19 at 18:43