简体   繁体   中英

How to create array and pass them in Node.js

I'd like to pass fetched data like following array .

 { category: ['Animals','Vehicles']

   difficulty: ['easy','medium']
 }

I tried something like following, getCategory.push(quiz.getCategory(2)),

But I encountered following errors.

Unexpected token.

I confused how to pass array like data.

If someone has opinon,please let me know.

Thanks

const API_KEY="https://opentdb.com/api.php?amount=10&type=multiple";
const fetch = require('node-fetch');
const Quiz=require("../public/javascripts/quiz");


module.exports={
    getQuiz:function(resp){
      fetch(API_KEY)
      .then(response => response.json())
      .then(json => { const quiz = new Quiz(json); 
            resp.send({
                getCategory:quiz.getCategory(1),
                getCategory.push(quiz.getCategory(2)),
                getDifficulty:quiz.getDifficulty(1),
                getDifficulty.push(quiz.getDifficulty(2))
  
            });
        });
    }
};

My class is following.

class Quiz {
    constructor(quizData){
        this._quizzes = quizData.results;
        this._correctAnswersNum = 0;
    }
    
    getNumOfQuiz(){
        return this._quizzes.length;
    }
    
    getCategory(index){
        return this._quizzes[index-1].category;
    }
    getDifficulty(index){
        return this._quizzes[index-1].difficulty;
    }
}
module.exports = Quiz;

fetch(API_KEY) returned something like following.

 results: 
   [ { category: 'Animals',
       type: 'multiple',
       difficulty: 'easy',
       question: 'What do you call a baby bat?',
       correct_answer: 'Pup',
       incorrect_answers: [Array] },
     { category: 'Vehicles',
       type: 'multiple',
       difficulty: 'medium',
       question: 'Which supercar company is from Sweden?',
       correct_answer: 'Koenigsegg',
       incorrect_answers: [Array] },
     { category: 'Entertainment: Board Games',
       type: 'multiple',
       difficulty: 'hard',
       question: 'Which board game was first released on February 6th, 1935?',
       correct_answer: 'Monopoly',
       incorrect_answers: [Array] }]

I didn't see how exactly we need to use the Class methods in this implementation.. But we can go as follows.

This is the data we are receiving

const data = [ { category: 'Animals',
       type: 'multiple',
       difficulty: 'easy',
       question: 'What do you call a baby bat?',
       correct_answer: 'Pup',
       incorrect_answers: [Array] },
     { category: 'Vehicles',
       type: 'multiple',
       difficulty: 'medium',
       question: 'Which supercar company is from Sweden?',
       correct_answer: 'Koenigsegg',
       incorrect_answers: [Array] },
     { category: 'Entertainment: Board Games',
       type: 'multiple',
       difficulty: 'hard',
       question: 'Which board game was first released on February 6th, 1935?',
       correct_answer: 'Monopoly',
       incorrect_answers: [Array] }];

The data structure we want to send as in response.

const finalResponse = {
  category : [],
  difficulty : [] 
}

Looping over actual data, and collect the data in finalResponse . May be if you already know the index of data you can make the use if Class as mentioned in question. For now we have used data array prototype method forEach to loop over each datum as shown below.

data.forEach(function({category, difficulty}){
    finalResponse.category.push(category);
    finalResponse.category.push(difficulty);
})

finally send the collected data as response

res.send(finalResponse);

Answer 1 (quick fix):

const API_KEY="https://opentdb.com/api.php?amount=10&type=multiple";
const fetch = require('node-fetch');
const Quiz=require("../public/javascripts/quiz");


module.exports={
    getQuiz:function(resp){
      fetch(API_KEY)
      .then(response => response.json())
      .then(json => { const quiz = new Quiz(json); 
            resp.send({
                getCategory:[quiz.getCategory(1), quiz.getCategory(2)],
                getDifficulty:[quiz.getDifficulty(1),quiz.getDifficulty(2)]
  
            });
        });
    }
};

Answer 2 (correct way):

  • class Quiz: introduce new method to get array | getPropArray() // I'm bad at naming
class Quiz {
    constructor(quizData){
        this._quizzes = quizData.results;
        this._correctAnswersNum = 0;
    }
    
    getNumOfQuiz(){
        return this._quizzes.length;
    }
    
    getCategory(index){
        return this._quizzes[index-1].category;
    }
    getDifficulty(index){
        return this._quizzes[index-1].difficulty;
    }
    /**
    * get array of prop (property) 
    * @param {string} prop
    * @param {number} start
    * @param {number} end
    */
    getPropArray(prop, start=1, end=this._quizzes.length){
        let res = [];
        for (let i=start-1; i<=end-1; i++){
             res.push(this._quizzes[i][prop]);
        }
        return res;
    }
}
module.exports = Quiz;

now you can add new property to your response if you want, idk what logic you wanna use to choose result[index] but here^ you can apply a range.

const API_KEY="https://opentdb.com/api.php?amount=10&type=multiple";
const fetch = require('node-fetch');
const Quiz=require("../public/javascripts/quiz");


module.exports={
    getQuiz:function(resp){
      fetch(API_KEY)
      .then(response => response.json())
      .then(json => { const quiz = new Quiz(json); 
            resp.send({
                getCategory: quiz.getPropArray('category' ),
                getDifficulty: quiz.getPropArray('difficulty')
            });
        });
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM