Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

You’re looking for the .map() Javascript Array method

Here is an example that should give you the array of values you are looking for.

const correct_answer_array = apipresave.map(item => item.correct_answer)
// ["Moving Picture","Gigahertz","Final"] 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading