4

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.

asked Jan 30, 2020 at 4:55

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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
 };
 })
 }
 })
answered Jan 30, 2020 at 5:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.