Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

94
Views
Javascript Objects - Check for and loop through arrays in object

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);
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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));
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!