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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't even notice I left out part of the code. My apologies.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.