0

My Structure of data will be like below

 var data = {"Questions" : [
                  {"QID":"Q1","S":"2"},
                  {"QID":"Q2","T":"12"},   
                  {"QID":"Q3","U":"22"}], // Also please suggest me to improve this to make parsing easier
             "Share" : "Yes"
            };
 for(var item in data.Questions)
 {
    if(this.QID == "Q2") // this.QID returns me undefined
    {
        // I want to retrieve the total object i.e
        // {"QID":"Q2","T":"12"} should be returned
    }
 }

Why does this.QID return me undefined? How can I retrieve the total object, i.e. {"QID":"Q2","T":"12"}?

gilly3
  • 87,962
  • 25
  • 144
  • 176
Exception
  • 8,111
  • 22
  • 85
  • 136
  • 1
    @minitech Read the Question please.. I have specified comments on what problems I am getting... I don't think I have written non-English characters above :-) – Exception Dec 30 '11 at 06:10
  • My point being: "What question?" You haven't specified anything. Your question makes little sense and you need to elaborate. Where does `this.QID` come from, for instance? – Ry- Dec 30 '11 at 06:11
  • @minitech I thought there might be problem and I have specified comment to that line :-) – Exception Dec 30 '11 at 06:12

2 Answers2

1

Change your iteration code to this:

var questions = data.Questions;
for (var i = 0; i < questions.length; i++) {
    if (questions[i].QID == "Q2") {
        // questions[i] is all the data of this array element
    } 
}

Arrays should NOT be iterated with for (x in array). That type of iteration iterates over object properties which will also pick up array elements, but it's not recommended. Use array indexing or .forEach() in a modern browser to iterate through an array in a predictable order and without any other properties showing up in the iteration.

In addition, the way you were trying to do the iteration does not set this to anything so you can't use it to access the array element.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

Don't iterate Arrays using for .. in loops. Use a regular for loop or Array.forEach()*.

That aside, this is not going to be an item in your Array. You need:

if (data.Questions[item].QID == "Q2") {
    ...
}

Using a regular for loop:

for (var i = 0; i < data.Questions.length; i++) {   
    if (data.Questions[i].QID == "Q2") {   
        ...
    }    
}   

Or, my preferred method, Array.forEach():

data.Questions.forEach(function (item) {
    if (item.QID == "Q2") {
        ...
    }
});

*Older browsers don't natively support Array.forEach(), but you can add it in yourself. See the compatibility notes for an implementation you can use in your code for older browsers.

Community
  • 1
  • 1
gilly3
  • 87,962
  • 25
  • 144
  • 176