Reputation: 2384
I am passing data into array from mysql query and getting it into javascript which is display like this
Data:{"0":[{"Question":"abc","Answer":"abc 123"},{"Question":"xyz","Answer":"xyz 123 "}], "message":"Success"}
Now I want to get all Question in one variable and related FAQ_Answer in another variable and display like
Question : abc Answer : abc 123
Question : xyz Answer : xyz 123
But the problem is that I don't know how to get related question and its answer from an array.
I tried all the methods like data[0][0] or etc. but it is giving me undefined or [object,object] type of output.
Upvotes: 0
Views: 139
Reputation: 35314
Here's how it can be done:
var data = {Data:{"0":[{"Question":"abc","Answer":"abc 123"},{"Question":"xyz","Answer":"xyz 123 "}], "message":"Success"}};
var qaList = data.Data['0'];
// build HTML in div from questions and answers
var div = document.getElementById('qa');
for (var i = 0; i < qaList.length; ++i) {
var qa = qaList[i];
div.innerHTML += 'Question : '+qa.Question+' Answer : '+qa.Answer+'<br/>';
} // end for
Upvotes: 0
Reputation: 1950
You need to read some documentation about javascript syntax a little :p .
In this case, let's assume you have =:
var data = {"0":[{"Question":"abc","Answer":"abc 123"}]};
It is read like this: data is an object, containing a single key named "0", which is a reference to an array. The array contains a single entry. That entry is an object containing 2 keys, "Question" and "Answer", each being a string.
So, with that said:
data // is the object
data[0] // references the array of questions, note that it is in fact data["0"]
data[0][0] // references the first entry in the array of questions
data[0][0].Question // contains the first question's text
data[0][0].Answer // contains the first question's answer
Typically, you'd make a variable that represents what your dealing with to make it clear to whoever reads the code, e.g.
var first_question = data[0][0];
and use the properties from then on.
Upvotes: 3