简体   繁体   中英

How can I get the index of array element inside object?

const questions = [
    {
      "question": "What is the scientific name of a butterfly?",
      "answers": ["Apis", "Coleoptera", "Formicidae", "Rhopalocera"],
      "correctIndex": 3
    },
    {
      "question": "How hot is the surface of the sun?",
      "answers": ["1,233 K", "5,778 K", "12,130 K", "101,300 K"],
      "correctIndex": 1
    },
]

I'm trying this way but return -1:

console.log(questions.findIndex(value => value.answers.indexOf() === 'Apis'));

For example if wanna get the indexOf 'Apis', i get -1.

I'm trying to compare 'CorrectIndex' value with index of answers array value and return if its correct or not.

If I understood correctly, you want to get the index of element in answers array of this object. try this:

console.log(questions.map(value => value.answers.indexOf('Apis')));

this will give you an array of indexes whose value is "Apis".

If you have duplicate values in same array, you can do this:

console.log(questions.map(value => [value.answers.indexOf('Apis')]));

This will store an array of the array in which you can get the indexes of "Apis" of each object.

I'm trying to compare 'CorrectIndex' value with index of answers array value and return if its correct or not.

Try this

 const questions = [ { "question": "What is the scientific name of a butterfly?", "answers": ["Apis", "Coleoptera", "Formicidae", "Rhopalocera"], "correctIndex": 3 }, { "question": "How hot is the surface of the sun?", "answers": ["1,233 K", "5,778 K", "12,130 K", "101,300 K"], "correctIndex": 1 }, ] console.log(questions.map(value => value.answers.indexOf('Apis') === value.correctIndex));

You just used indexOf in a wrong way. That's quite simple to fix:

 const questions = [ { question: "What is the scientific name of a butterfly?", answers: ["Apis", "Coleoptera", "Formicidae", "Rhopalocera"], correctIndex: 3 }, { question: "How hot is the surface of the sun?", answers: ["1,233 K", "5,778 K", "12,130 K", "101,300 K"], correctIndex: 1 } ] questions.forEach(question => { console.log(question.answers.indexOf('Apis')) });

Realize that indexOf is a function and recives a string.

why are u comparing value.answers.indexOf()

the correct syntax should be

console.log(questions.findIndex(value => value.answers.indexOf('element')));

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