如何打印嵌套对象的所有值 [英] how to print all values of a nested object
本文介绍了如何打印嵌套对象的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个这样的嵌套对象:
There is a nested object like that:
var conversation = {
'John': {
1: 'Test message 1',
2: 'Test message 2',
'Reply': {
3: 'Test message 3',
4: 'Test message 4'
}
},
'Jack': {
5: 'Test message 5',
6: 'Test message 6'
}
};
我需要获得所有最终值,因此对于该示例,它是:
I need to get all final values, so for that example, it is:
Test message 1
Test message 2
Test message 3
Test message 4
Test message 5
Test message 6
如何迭代对象?在jQuery或JavaScript中是否有任何内置函数?
How to iterate over the object? Is there any built-in function in jQuery or JavaScript?
推荐答案
您可以使用一些递归来检查密钥是否存在迭代是否是一个对象,然后打印:
You can use some recursion to check to see if the key being iterated over is an object or not, then print:
function printValues(obj) {
for (var key in obj) {
if (typeof obj[key] === "object") {
printValues(obj[key]);
} else {
console.log(obj[key]);
}
}
}
printValues(conversation);
演示: http: //jsfiddle.net/c7th1t8r/
这篇关于如何打印嵌套对象的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文