优化for循环,将对象键值推入数组

时间:2018-10-04 16:57:23

标签: javascript arrays

我有一个包含问题的对象,每个问题都有一个不同的难度,用allQuiz[x].difficulty表示。

我写了一个for循环,它将按其相对难度类别对问题进行排序。例如,难度25 =容易,难度50 =中等。

这是对象结构的一部分:

 {
    "id": "41",
    "category": "TV & Movies",
    "locales": "GB#US",
    "difficulty": "50",
    "question": {
       "Voice": "Which fictional city is the home of Batman?",
       "Display": "Which fictional city is the home of Batman?"
    },
    "answer": {
       "Voice": "Gotham City",
       "Display": "Gotham City"
    }
 },
 {
    "id": "42",
    "category": "TV & Movies",
    "locales": "GB#US",
    "difficulty": "50",
    "question": {
       "Voice": "The Hunchback of Notre Dame was also known as?",
       "Display": "The Hunchback of Notre Dame was also known as?"
    },
    "answer": {
       "Voice": "Quasimodo",
       "Display": "Quasimodo"
    }
 },
 {
    "id": "43",
    "category": "TV & Movies",
    "locales": "GB#US",
    "difficulty": "75",
    "question": {
       "Voice": "The title role of the 1990 movie Pretty Woman was played by which actress?",
       "Display": "The title role of the 1990 movie Pretty Woman was played by which actress?"
    },
    "answer": {
       "Voice": "Julia Roberts",
       "Display": "Julia Roberts"
    }
 },
 {
    "id": "44",
    "category": "TV & Movies",
    "locales": "GB#US",
    "difficulty": "75",
    "question": {
       "Voice": "Which Tom Hanks movie won the Academy Award for Best Picture in 1994?",
       "Display": "Which Tom Hanks movie won the Academy Award for Best Picture in 1994?"
    },
    "answer": {
       "Voice": "Forrest Gump",
       "Display": "Forrest Gump"
    }
 },
 {
    "id": "45",
    "category": "TV & Movies",
    "locales": "GB#US",
    "difficulty": "100",
    "question": {
       "Voice": "Jonny Depp starred as Jack Sparrow in which series of movies?",
       "Display": "Jonny Depp starred as Jack Sparrow in which series of movies?"
    },
    "answer": {
       "Voice": "Pirates of the Caribbean",
       "Display": "Pirates of the Caribbean"
    }
 },
 {
    "id": "46",
    "category": "TV & Movies",
    "locales": "GB#US",
    "difficulty": "100",
    "question": {
       "Voice": "Marion Crane is the tragic figure in which cult horror film?",
       "Display": "Marion Crane is the tragic figure in which cult horror film?"
    },
    "answer": {
       "Voice": "Psycho",
       "Display": "Psycho"
    }
 },


    {
        "id": "47",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "25",
        "question": {
           "Voice": "Alexander Graham Bell invented which communication tool?",
           "Display": "Alexander Graham Bell invented which communication tool?"
        },
        "answer": {
           "Voice": "Telephone",
           "Display": "Telephone"
        }
     },
 {
        "id": "48",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "75",
        "question": {
           "Voice": "Steve jobs was the founder of which tech giant?",
           "Display": "Steve jobs was the founder of which tech giant?"
        },
        "answer": {
           "Voice": "Apple",
           "Display": "Apple"
        }
     },
     {
        "id": "49",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "75",
        "question": {
           "Voice": "Which year was Amazon founded?",
           "Display": "Which year was Amazon founded?"
        },
        "answer": {
           "Voice": "1994",
           "Display": "1994"
        }
     },
     {
        "id": "50",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "100",
        "question": {
           "Voice": "What is the natural habitat of an arboreal creature?",
           "Display": "What is the natural habitat of an arboreal creature?"
        },
        "answer": {
           "Voice": "Trees",
           "Display": "Trees"
        }
     },
     {
        "id": "51",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "25",
        "question": {
           "Voice": "What is a geiger counter used to detect?",
           "Display": "What is a geiger counter used to detect?"
        },
        "answer": {
           "Voice": "Radiation",
           "Display": "Radiation"
        }
     },
     {
        "id": "52",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "50",
        "question": {
           "Voice": "What element on the periodic table has the chemical symbol H?",
           "Display": "What element on the periodic table has the chemical symbol H?"
        },
        "answer": {
           "Voice": "Hydrogen",
           "Display": "Hydrogen"
        }
     },
     {
        "id": "53",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "50",
        "question": {
           "Voice": "What is the more common name for Nitrous Oxide? �",
           "Display": "What is the more common name for Nitrous Oxide? �"
        },
        "answer": {
           "Voice": "Laughing gas",
           "Display": "Laughing gas"
        }
     },
     {
        "id": "54",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "75",
        "question": {
           "Voice": "In computing, how many bits are in a byte?",
           "Display": "In computing, how many bits are in a byte?"
        },
        "answer": {
           "Voice": "Eight",
           "Display": "Eight"
        }
     },
     {
        "id": "55",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "50",
        "question": {
           "Voice": "Who discovered Penicillin?",
           "Display": "Who discovered Penicillin?"
        },
        "answer": {
           "Voice": "Alexander Fleming",
           "Display": "Alexander Fleming"
        }
     },
     {
        "id": "56",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "25",
        "question": {
           "Voice": "Which planet in our solar system is closest to the sun?",
           "Display": "Which planet in our solar system is closest to the sun?"
        },
        "answer": {
           "Voice": "Mercury",
           "Display": "Mercury"
        }
     },
     {
        "id": "57",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "25",
        "question": {
           "Voice": "What subject did Mark Zuckerburg study at university?",
           "Display": "What subject did Mark Zuckerburg study at university?"
        },
        "answer": {
           "Voice": "Computer Science",
           "Display": "Computer Science"
        }
     },

这是我的尝试:

var allQuiz= myObject;

var easyQuiz =[];
var mediumQuiz =[];
var hardQuiz =[];
var veryhardQuiz =[];


for(let x=0;x<allQuiz.length;x++){

    if(allQuiz[x].difficulty==25){
        let tmp = [];
        tmp.push((allQuiz[x]).id);
    tmp.push((allQuiz[x]).question.Display);
    tmp.push((allQuiz[x]).answer.Display);
    easyQuiz.push(tmp);
}
else if(allQuiz[x].difficulty==50){
    let tmp =[];
    tmp.push((allQuiz[x]).id);
    tmp.push((allQuiz[x]).question.Display);
    tmp.push((allQuiz[x]).answer.Display);
    mediumQuiz.push(tmp);

}
else if(allQuiz[x].difficulty==75){
    let tmp =[];
    tmp.push((allQuiz[x]).id);
    tmp.push((allQuiz[x]).question.Display);
    tmp.push((allQuiz[x]).answer.Display);
    hardQuiz.push(tmp);

}
else {
    let tmp = [];
    tmp.push((allQuiz[x]).id);
    tmp.push((allQuiz[x]).question.Display);
    tmp.push((allQuiz[x]).answer.Display);
    veryhardQuiz.push(tmp);
} 
}

但是,我注意到这里有很多重复的代码,改变的唯一因素是即时推送到的测验类别以及问题的难度。

如何使此for循环更优雅或更有效?

3 个答案:

答案 0 :(得分:2)

在不牺牲可读性的前提下,我认为我不能使其更加简洁:

var allQuiz= myObject;
var quizzesByDifficulty = { 25: [], 50: [], 75: [], 100: [] };
for(var x in allQuiz)
{
  var quiz = allQuiz[x];
  var quizzes = quizzesByDifficulty[quiz.difficulty];
  quizzes.push([
    quiz.id,
    quiz.question.Display,
    quiz.answer.Display
  ]);
}

如果您需要将每个难度作为自己的数组,则可以始终这样做:

var easy = quizzesByDifficult[25];
var medium = quizzesByDifficulty[50];
// etc.

编辑:当然,以上假设仅存在4个困难。如果这是您无法做出的假设,则仍然可以修改代码以解决该问题:

var allQuiz= myObject;
var quizzesByDifficulty = {};
for(var x in allQuiz)
{
  var quiz = allQuiz[x];

  if (!quizzesByDifficulty[quiz.difficulty]) {
    quizzesByDifficulty[quiz.difficulty] = [];
  }

  var quizzes = quizzesByDifficulty[quiz.difficulty];
  quizzes.push([
    quiz.id,
    quiz.question.Display,
    quiz.answer.Display
  ]);
}

答案 1 :(得分:1)

array.reduce是用于此类数据转换任务的便捷功能。这个想法是创建一个难度映射到值数组的键对象。最后,可以将生成的对象拆分为四个所需的结构或按原样使用(如果需要,可以将键从难度编号映射到难度词)。

var allQuiz = [{ "id": "41", "category": "TV & Movies", "locales": "GB#US", "difficulty": "50", "question": { "Voice": "Which fictional city is the home of Batman?", "Display": "Which fictional city is the home of Batman?" }, "answer": { "Voice": "Gotham City", "Display": "Gotham City" } }, { "id": "42", "category": "TV & Movies", "locales": "GB#US", "difficulty": "50", "question": { "Voice": "The Hunchback of Notre Dame was also known as?", "Display": "The Hunchback of Notre Dame was also known as?" }, "answer": { "Voice": "Quasimodo", "Display": "Quasimodo" } }, { "id": "43", "category": "TV & Movies", "locales": "GB#US", "difficulty": "75", "question": { "Voice": "The title role of the 1990 movie Pretty Woman was played by which actress?", "Display": "The title role of the 1990 movie Pretty Woman was played by which actress?" }, "answer": { "Voice": "Julia Roberts", "Display": "Julia Roberts" } }, { "id": "44", "category": "TV & Movies", "locales": "GB#US", "difficulty": "75", "question": { "Voice": "Which Tom Hanks movie won the Academy Award for Best Picture in 1994?", "Display": "Which Tom Hanks movie won the Academy Award for Best Picture in 1994?" }, "answer": { "Voice": "Forrest Gump", "Display": "Forrest Gump" } }, { "id": "45", "category": "TV & Movies", "locales": "GB#US", "difficulty": "100", "question": { "Voice": "Jonny Depp starred as Jack Sparrow in which series of movies?", "Display": "Jonny Depp starred as Jack Sparrow in which series of movies?" }, "answer": { "Voice": "Pirates of the Caribbean", "Display": "Pirates of the Caribbean" } }, { "id": "46", "category": "TV & Movies", "locales": "GB#US", "difficulty": "100", "question": { "Voice": "Marion Crane is the tragic figure in which cult horror film?", "Display": "Marion Crane is the tragic figure in which cult horror film?" }, "answer": { "Voice": "Psycho", "Display": "Psycho" } }, { "id": "47", "category": "Science & Technology", "locales": "GB#US", "difficulty": "25", "question": { "Voice": "Alexander Graham Bell invented which communication tool?", "Display": "Alexander Graham Bell invented which communication tool?" }, "answer": { "Voice": "Telephone", "Display": "Telephone" } }, { "id": "48", "category": "Science & Technology", "locales": "GB#US", "difficulty": "75", "question": { "Voice": "Steve jobs was the founder of which tech giant?", "Display": "Steve jobs was the founder of which tech giant?" }, "answer": { "Voice": "Apple", "Display": "Apple" } }, { "id": "49", "category": "Science & Technology", "locales": "GB#US", "difficulty": "75", "question": { "Voice": "Which year was Amazon founded?", "Display": "Which year was Amazon founded?" }, "answer": { "Voice": "1994", "Display": "1994" } }, { "id": "50", "category": "Science & Technology", "locales": "GB#US", "difficulty": "100", "question": { "Voice": "What is the natural habitat of an arboreal creature?", "Display": "What is the natural habitat of an arboreal creature?" }, "answer": { "Voice": "Trees", "Display": "Trees" } }, { "id": "51", "category": "Science & Technology", "locales": "GB#US", "difficulty": "25", "question": { "Voice": "What is a geiger counter used to detect?", "Display": "What is a geiger counter used to detect?" }, "answer": { "Voice": "Radiation", "Display": "Radiation" } }, { "id": "52", "category": "Science & Technology", "locales": "GB#US", "difficulty": "50", "question": { "Voice": "What element on the periodic table has the chemical symbol H?", "Display": "What element on the periodic table has the chemical symbol H?" }, "answer": { "Voice": "Hydrogen", "Display": "Hydrogen" } }, { "id": "53", "category": "Science & Technology", "locales": "GB#US", "difficulty": "50", "question": { "Voice": "What is the more common name for Nitrous Oxide? �", "Display": "What is the more common name for Nitrous Oxide? �" }, "answer": { "Voice": "Laughing gas", "Display": "Laughing gas" } }, { "id": "54", "category": "Science & Technology", "locales": "GB#US", "difficulty": "75", "question": { "Voice": "In computing, how many bits are in a byte?", "Display": "In computing, how many bits are in a byte?" }, "answer": { "Voice": "Eight", "Display": "Eight" } }, { "id": "55", "category": "Science & Technology", "locales": "GB#US", "difficulty": "50", "question": { "Voice": "Who discovered Penicillin?", "Display": "Who discovered Penicillin?" }, "answer": { "Voice": "Alexander Fleming", "Display": "Alexander Fleming" } }, { "id": "56", "category": "Science & Technology", "locales": "GB#US", "difficulty": "25", "question": { "Voice": "Which planet in our solar system is closest to the sun?", "Display": "Which planet in our solar system is closest to the sun?" }, "answer": { "Voice": "Mercury", "Display": "Mercury" } }, { "id": "57", "category": "Science & Technology", "locales": "GB#US", "difficulty": "25", "question": { "Voice": "What subject did Mark Zuckerburg study at university?", "Display": "What subject did Mark Zuckerburg study at university?" }, "answer": { "Voice": "Computer Science", "Display": "Computer Science" } },];

const quizzes = allQuiz.reduce((a, e) => {
  if (!a[e.difficulty]) {
    a[e.difficulty] = [];
  }
  
  a[e.difficulty].push([e.id, e.question.Display, e.answer.Display]);
  return a;
}, {});

const easyQuiz = quizzes["25"];
const mediumQuiz = quizzes["50"];
const hardQuiz = quizzes["75"];
const veryHardQuiz = quizzes["100"];

console.log(easyQuiz);
console.log(mediumQuiz);
console.log(hardQuiz);
console.log(veryHardQuiz);

答案 2 :(得分:0)

我假设allQuiz将是一个数组。是的,就像您提到的那样,可以进行很多优化。

const allQuiz = [{
  id: 1,
  question: {
    Display: 'abc'
  },
  answer: {
    Display: '123'
  },
  difficulty: 25
}];

const sortedQuiz = {
  easyQuiz: [],
  mediumQuiz: [],
  hardQuiz: [],
  veryhardQuiz: [],
}

allQuiz.reduce((acc, quiz) => {
  let category;

  // Following if..else can also be pulled out into a seperate function
  if (quiz.difficulty === 25) {
    category = acc.easyQuiz;
  } else if (quiz.difficulty === 50) {
    category = acc.mediumQuiz;
  } else if (quiz.difficulty === 75) {
    category = acc.hardQuiz;
  } else {
    category = acc.veryhardQuiz;
  }

  category.push([quiz.id, quiz.question.Display, quiz.answer.Display]);

  return acc;
}, sortedQuiz)


const appDiv = document.getElementById('app');
appDiv.innerHTML = `<p>${JSON.stringify(sortedQuiz)}</p>`;
<div id="app"></div>