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
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();
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"
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);