Hi I have been trying make this following array
[
{
"name": "Study",
"questions": [
{
"question": "Would you Love to learn about Java?",
"answer": "Yes"
}
]
},
{
"name": "Song",
"questions": [
{
"question": "Would you Love to learn about song?",
"answer": "Yes"
},
{
"question": "Would you Love to learn about rock?",
"answer": "No"
}
]
}
]
To this
[
{
"questions": [
{
"question": "Would you Love to learn about Java?",
"answer": "Yes",
"name": "Study"
}
]
},
{
"questions": [
{
"question": "Would you Love to learn about song?",
"answer": "Yes",
"name": "Song"
},
{
"question": "Would you Love to learn about rock?",
"answer": "No",
"name": "Song"
}
]
}
]
I have tried to map to two arrays ( from name and questions) and tried to combined them , but I can't make it work for multiple arrays in questions. How can I make this ? Is there any loadash way too accomplish this easily. But I'm trying to do this in Vanilla JavaScript way.
2 Answers 2
You can try with double .map():
let input = [
{
"name": "Study",
"questions": [
{
"question": "Would you Love to learn about Java?",
"answer": "Yes"
}
]
},
{
"name": "Song",
"questions": [
{
"question": "Would you Love to learn about song?",
"answer": "Yes"
},
{
"question": "Would you Love to learn about rock?",
"answer": "No"
}
]
}
]
let result = input.map(({name, questions}) => ({ questions: questions.map(q => ({name, ...q })) }));
console.log(result);
answered Jan 30, 2020 at 4:59
mickl
50.1k9 gold badges71 silver badges99 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Try following
let arr1 = [
{
"name": "Study",
"questions": [
{
"question": "Would you Love to learn about Java?",
"answer": "Yes"
}
]
},
{
"name": "Song",
"questions": [
{
"question": "Would you Love to learn about song?",
"answer": "Yes"
},
{
"question": "Would you Love to learn about rock?",
"answer": "No"
}
]
}
]
arr1.map((element, index) => {
console.log(element); console.log(index); return
{
questions: element.questions.map((e, i) => {
console.log(e); console.log(i); return {
...e,
name: element.name
};
})
}
})
Comments
lang-js