Skip to content
Advertisement

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

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement