Estoy tratando de recorrer un objeto literal y si una propiedad es una matriz, también quiero recorrer eso. La propiedad de amigos de este objeto es una matriz, ¿cómo probaría para ver si es iterable y luego recorrerla?
Gracias por adelantado,
firstName: 'Jonas', lastName: 'Schmedtmann', age: 2037 - 1991, job: 'teacher', friends: ['Michael', 'Peter', 'Steven'], }; const myObj = Object.entries(jonas); for (const [key, val] of myObj) { //Some conditional statement here testing for an interable //Then loop through it to the console. console.log(key, val); }Todas las matrices son instancias de la clase Array en Javascript, por lo que puede usar var instanceof Array que devuelve un valor booleano para verificar si un elemento es una matriz o no, y luego repetirlo como desee.
const obj = { firstName: 'Jonas', lastName: 'Schmedtmann', age: 2037 - 1991, job: 'teacher', friends: ['Michael', 'Peter', 'Steven'], }; const myObj = Object.entries(obj); for (const [key, val] of myObj) { //Some conditional statement here testing for an interable //Then loop through it to the console. if (val instanceof Array) { console.log('element is an array, printing now') print(val); } else console.log(key, val); } function print(ar) { ar.forEach(x => console.log(x)); }