Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Bill
Joe
Mary
Rick
Ricky
Liz
Lisa
Beth

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading