0
var list=[
{
    color_1: "red",
    color_2: "red_1",
    value: "#f00"
},
{
    color_1: "green",
    color_2: "red_5",
    value: "#0f0"
},
{
    color_1: "blue",
    color_2: "red",
    value: "#00f"
},
{
    color_1: "cyan",
    color_2: "red",
    value: "#0ff"
},
{
    color_1: "magenta",
    color_2: "red",
    value: "#f0f"
},
{
    color_1: "yellow",
    color_2: "red",
    value: "#ff0"
},
{
    color_1: "black",
    color_2: "red",
    value: "#000"
}

];

in my json list i am getting dyanamic columns from back end like color_1,color_2,color_3,color_4....color_n upto n number of columns in json objects, i want to print them on console using for loop ,but i am getting undefined as output could you please tell me where i am getting wrong below is code

function callMe(){

    list.forEach(function(element, i) {
    for(var j=1;j<3;j++){

            console.log(element.color_+j);
        }
    });
}
amol
  • 1
  • 1

3 Answers3

1

You need a proper property accessor with brackets and a string.

console.log(element['color_' + j]);

function callMe() {
    list.forEach(function(element, i) {
        for (var j = 1; j < 3; j++) {           // var instead of int
            console.log(element['color_' + j]); // brackets
        }
    });
}

var list = [{ color_1: "red", color_2: "red_1", value: "#f00" }, { color_1: "green", color_2: "red_5", value: "#0f0" }, { color_1: "blue", color_2: "red", value: "#00f" }, { color_1: "cyan", color_2: "red", value: "#0ff" }, { color_1: "magenta", color_2: "red", value: "#f0f" }, { color_1: "yellow", color_2: "red", value: "#ff0" }, { color_1: "black", color_2: "red", value: "#000" }];

callMe();
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

I would use console.log(element["color_"+j])

Hope that helps!

Danyman
  • 63
  • 1
  • 9
0

To access an entry with a computed key you should use square brackets like this:

console.log(element[“color_”+j]);

The way you tried first gets element.color_ which is undefined, then adds j to undefined.

Always Learning
  • 5,510
  • 2
  • 17
  • 34