[英]How to iterate over JavaScript object when value of a value can be object?
Edited question . 编辑的问题 。 Thanks to @WiktorZychla for waking my Monday brain about recursion.
感谢@WiktorZychla唤醒了我周一关于递归的知识。 Following code is now working as it should.
下面的代码现在可以正常工作了。
If I have an object like this dummy here: 如果我在这里有一个像这样的假人的对象:
const dummy = {
a: 1,
b: 2,
c: {
d: 3,
e: {
f: 4
}
},
g: 5
};
I can iterate trough it with: 我可以用以下方法迭代它:
const xavier = (value, s) => {
for (const key in value) {
if (value.hasOwnProperty(key)) {
if (typeof value[key] === 'object' && value[key] !== null) {
xavier(value[key], s + '.' + key);
} else {
console.log(s + '.' + key + ' ' + value[key]);
}
}
}
};
This now prints the following: 现在将打印以下内容:
.a 1
.b 2
.c.d 3
.c.e.f 4
.g 5
after hard work i make a function that loop on any object: this will definitly iterate on how much level you want please just take a look on it 经过艰苦的工作,我制作了一个可以在任何对象上循环的函数:这将最终迭代您想要的级别,请看看它
arr = []; obj = { a: 1, b: 2, c: { d: 3, e: { f: 4 } } } function iter(x){ for(i in x){ if(typeof(x[i])=="object"){ iter(x[i]); }else{ arr.push(x[i]); }}} iter(obj); document.write(arr.join(','));
<!DOCTYPE html> <html> <body></body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.