[英]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);
}
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所有数组都是 Javascript 中
Array
类的实例,因此您可以使用var instanceof Array
返回一个布尔值来检查元素是否为数组,然后根据需要对其进行迭代
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)); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.