1

I have two array objects and need to use those two arrays in a json object. How to achieve it in react?

let qn = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
let ans= [false, false, false, false, false, false, false, false, false, false];

I need to convert the above two arrays below like this for the purpose of database insertion.

options: [{qn: "1", ans: false}, {qn: "2", ans: false}, ....., {qn: "10", ans: false}]

1 Answer 1

3

You could use map with index

let qn = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
let ans = [false, true, false, false, false, false, false, false, false, true]

const res = {
  options: qn.map((q, index) => ({
    qn: q,
    ans: ans[index],
  })),
}

console.log(res)

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

5 Comments

let text = this.props.data.matrix.options; let userAnswer = []; for (let j = 0; j < text.length; j++) { userAnswer.push(false); } const options = this.props.data.matrix.options.map((t, index) => ({ text: t, userAnswer: userAnswer[index], })); console.log(options);
Your comment on this question has helped me a lot, but I need one more information.
I'm getting options: [{text: {text: "1"}, userAnswer: false}].... Instead of this format, I need like this : options: [{text: "1", userAnswer: false}].
@SureshKumarPasupulati you should use text: t.text instead of text: t, full: const options = this.props.data.matrix.options.map((t, index) => ({ text: t.text, userAnswer: userAnswer[index], }))
I'm glad that you helped me instantly....Thank you so much! @hgb123

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.