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

Time:02-10

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

CodePudding user response:

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"] 

CodePudding user response:

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
     
    }
  • Related