1

I am trying to loop through an object literal and if a property is an array, I want to loop through that as well. The friends property of this object is an array, how would I test to see if it's iterable, then loop through it?

Thanks in advance,

  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);
}
Musicman
  • 49
  • 6

1 Answers1

0

All arrays are instance of the Array class in Javascript so you can use var instanceof Array which returns a boolean to check if an element is an array or not, then iterate through it as you wish

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));
}
AnanthDev
  • 1,605
  • 1
  • 4
  • 14