0

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation and detailed answer, i'll follow that steps for future use and for my knowledge. But another answer is exact what i want so i marked it as the right answer.
0

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

http://jsfiddle.net/61uv7jnj/

1 Comment

This is exact what i need thanks for the jsfiddle demo ... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.