Home > OS >  How to combine data from an array and object and put together into an array in JavaScript?
How to combine data from an array and object and put together into an array in JavaScript?

Time:01-06

I have an array in which I have some string value holding the id along with answer selected and I have different object in which I have the detail about answer which is selected. The below array keep updated whenever we select an option from question.

arr = ["Q1A1", "Q2A3"]

assume Q1 is Question no. 1 and A1 is option selected from the question. And below I have an object for the corresponding Q1 which contained the detail about answers and this object also get change as we move over to Q2

{
id: "Q1",
answers: [
{
id: "Q1A1",
text: "Yes"
},
{
id: "Q1A2",
text: "No"
}  
]
}

same way I have any another object for Q2 if we select the answer in Q1, now we have different object for Q2

{
id: "Q2",
answers: [
{
id: "Q2A1",
text: "Test 1"
},
{
id: "Q2A2",
text: "Test 2"
},
{
id: "Q2A3",
text: "Test 3"
},
{
id: "Q2A4",
text: "Test 4"
}    
]
}

I need to lookup the object with the help of array which contain question and answer(eg, "Q1A1") with selected and need to find the text for answer selected i.e ("Yes") if u look into the above object for question 1. Hence I need put into the array like this way.

result = ["Q1_Yes","Q2_Test3"]

CodePudding user response:

This code will help you to get those results.

let selected = ["Q1A1", "Q2A3"];
let QA = [
  {
id: "Q1",
answers: [
{
id: "Q1A1",
text: "Yes"
},
{
id: "Q1A2",
text: "No"
}  
]
},
{
id: "Q2",
answers: [
{
id: "Q2A1",
text: "Test 1"
},
{
id: "Q2A2",
text: "Test 2"
},
{
id: "Q2A3",
text: "Test 3"
},
{
id: "Q2A4",
text: "Test 4"
}    
]
}
];
let all_answers = QA.reduce((allanswers,qa)=>(qa.answers.map(d=> allanswers[d.id]=[qa.id,d.text]),allanswers),{});

const result = selected.map(selected => all_answers[selected].join('_'))
console.log(result)

  • Related