Converting array objects into json in react

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}]

Upvotes: 1

Views: 305

Answers (1)

hgb123
hgb123

Reputation: 14871

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)

Upvotes: 3

Related Questions