Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

94
Visualizações
Looping through a dictionary in javascript with a list within the values

Not sure how to parse through a list of strings within a loop regarding this dictionary.

var student_nicknames = [    
    {name: "William",  nickname: "Bill"},
    {name: "Joseph",   nickname: "Joe"},
    {name: "Maria",    nickname: "Mary"},
    {name: "Richard",  nickname: ["Rick", "Ricky"]},
    {name: "Elizabeth",  nickname: ["Liz", "Lisa", "Beth"]}
];

total_nicknames = function(){
    student_nicknames.forEach(function(student) {
       console.log(student.nickname); 
    });
}

Output

Bill
Joe
Mary
[ 'Rick', 'Ricky' ]
[ 'Liz', 'Lisa', 'Beth' ]

Desired Output

Bill
Joe
Mary
Rick
Ricky
Liz
Lisa
Beth
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

All you need to do is to have an if condition to check if nickname property of each student is an array or not, if it is an array, then you can loop through it and print each item individually, otherwise follow your logic.

var student_nicknames = [
  { name: "William", nickname: "Bill" },
  { name: "Joseph", nickname: "Joe" },
  { name: "Maria", nickname: "Mary" },
  { name: "Richard", nickname: ["Rick", "Ricky"] },
  { name: "Elizabeth", nickname: ["Liz", "Lisa", "Beth"] }
];

const total_nicknames = function () {
  student_nicknames.forEach(function (student) {
    if (Array.isArray(student.nickname)) { // <- HERE
      student.nickname.forEach((e) => console.log(e));
    } else {
      console.log(student.nickname);
    }
  });
};

total_nicknames();
about 4 years ago · Juan Pablo Isaza Relatório

0

a simple solution based on recursion.

function total_nicknames(student_nicknames) {
    for(let i = 0; i < student_nicknames.length; i++){
      let student = student_nicknames[i];
        if(typeof student === 'object' && student !== null) {
          if(Array.isArray(student.nickname)){
            total_nicknames(student.nickname);
          }else {
            console.log(student.nickname);
          }
        }else {
          console.log(student);
        }
    }
  }


console.log(total_nicknames(student_nicknames));

/* output */
// "Bill"
// "Joe"
// "Mary"
// "Rick"
// "Ricky"
// "Liz"
// "Lisa"
// "Beth"
about 4 years ago · Juan Pablo Isaza Relatório

0

You can build a small recursive loop, by calling the total_nicknames function again, if student.nickname is an array. You also need to use || (OR) operator, to get the nickname (which would be a string, if it loops over the array) and not undefined (since string object doesn't have any nickname method/property).

var student_nicknames = [{
    name: "William",
    nickname: "Bill"
  },
  {
    name: "Joseph",
    nickname: "Joe"
  },
  {
    name: "Maria",
    nickname: "Mary"
  },
  {
    name: "Richard",
    nickname: ["Rick", "Ricky"]
  },
  {
    name: "Elizabeth",
    nickname: ["Liz", "Lisa", "Beth"]
  }
];

total_nicknames = function(arr) {
  arr.forEach(function(student) {
    if (Array.isArray(student.nickname)) {
      total_nicknames(student.nickname)
    } else
      console.log((student.nickname || student));
  });
}

total_nicknames(student_nicknames);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda