'how to pick some value from an object {} and put it into an array []

got some information from an API and now want to pick "correct_answer" property from all of them and then make an array from correct_answer here is the API information :

apipresave=[
  {question: "What does the "MP" stand for in MP3?",
   correct_answer: "Moving Picture",
   incorrect_answers: ["Music Player", "Multi Pass", "Micro Point"]},

  {question: "What does GHz stand for?", 
   correct_answer: "Gigahertz", 
   incorrect_answers: ["Gigahotz", "Gigahetz", "Gigahatz"]}, 

  {question: "In the programming language Java, which of these keywords would you put on a variable 
   to make sure it doesn't get modified?", 
   correct_answer: "Final", 
   incorrect_answers: ["Static", "Private", "Public"]},
]

btw I have already put this information on a const and have full access to them in code I have tried to loop over them and use push to get them but it didn't work I put it below :

   //puting all correct_answer  into an array 
   function correct_answer_array_func (){
         const correct_answer_array =[]
         for(let i =0 ; i<4;i++){
             correct_answer_array.push(apipresave[i].correct_answer) 
                 return correct_answer_array
         }    
    }

so how to obtain "correct_answer" from all the objects and put them in an array
the final result will be :

 correct_answer_array  =["Moving Picture","Gigahertz","Final"]  // correct_answer values


Solution 1:[1]

To answer the question in terms of the code you provide:

In the function correct_answer_array_func you immediately return after pushing one correct_answer to the array. Also, you hardcoded the length of the array, which I believe is not the best thing to do (is the API response guaranteed to be 4 objects?)

So, to make the function work, you need something similar to:

   //puting all correct_answer  into an array 
   function correct_answer_array_func (){
         const correct_answer_array =[]
         for(let i =0 ; i<apipresave.length;i++){
             correct_answer_array.push(apipresave[i].correct_answer) 
         }    
         return correct_answer_array
     
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tortellini Teusday