-1

I have some questions about my code. My code look like this

var data = {"Q1":"Male","Q5":"USA"};

var combine = [ {"Q1":"Male","Q5":"USA"},
        {"Q1":"Male","Q5":"Japan"}];

for(key in combine[0]){

   if(key.length > 1){
    var num = key.length;
    console.log(key, data.key);  
    }
}

My purpose is try to return data.Q1 and data.Q2 with use data.key but when i console.log(key, data.key);

Keys are Q1, Q5 but data.key is undefined i think its must be "Male" and "USA"

enter image description here

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
BBBBeloved
  • 75
  • 1
  • 1
  • 7

5 Answers5

2

Change console.log(key, data.key); to console.log(key, data[key]);

var data = {"Q1":"Male","Q5":"USA"};

var combine = [ {"Q1":"Male","Q5":"USA"},
                {"Q1":"Male","Q5":"Japan"}];

for(key in combine[0]){
        if(key.length > 1){
        var num = key.length;
        console.log(key, data[key]);     
        }
    }
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
1

Since key is dynamic, use [] bracket notation to access the property. This will allow you to evaluate key dynamically:

 var data = {"Q1":"Male","Q5":"USA"};

var combine = [ {"Q1":"Male","Q5":"USA"},
                {"Q1":"Male","Q5":"Japan"}];

for(key in combine[0]){
    if(key.length > 1){
    var num = key.length;
    console.log(key, data[key]);     
    }
}
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

key in combine[0] imply the key name of the object.

So key.length gives you the length of key i.e Q1 's length

use data[key] to get the whole object

var data = {
  "Q1": "Male",
  "Q5": "USA"
};

var combine = [{
    "Q1": "Male",
    "Q5": "USA"
  },
  {
    "Q1": "Male",
    "Q5": "Japan"
  }
];

for (key in combine[0]) {
  if (key.length > 1) {
    var num = key.length;
    console.log(key);
    console.log("key's length--", key.length);
    console.log("key's data--", data[key]);
  }
}
p u
  • 1,395
  • 1
  • 17
  • 30
0

Your data object is map. Try using data[key]

var data = {"Q1":"Male","Q5":"USA"};
var combine = [ {"Q1":"Male","Q5":"USA"},
                {"Q1":"Male","Q5":"Japan"}];
for(key in combine[0]){
   if(key.length > 1){
        var num = key.length;
        console.log(key, data[key]);     
   }
}
Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24
0

data.key tries to access property key in your data object which is undefined.

Try using [] brackets.

Example:

 var data = {"Q1":"Male","Q5":"USA"};

var combine = [ {"Q1":"Male","Q5":"USA"},
                {"Q1":"Male","Q5":"Japan"}];

for(key in combine[0]){
        if(key.length > 1){
        var num = key.length;
        console.log(key, data[key]);     
        }
    }
dRoyson
  • 1,466
  • 3
  • 14
  • 25