将对象展平为数组? [英] Flatten object to array?
本文介绍了将对象展平为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用一个对象作为哈希表。我想快速打印出它的内容(例如 alert()
)。是否内置了将哈希转换为(键,值)对的数组?
I'm using an object as a hash table. I'd like to quickly print out its contents (for alert()
for instance). Is there anything built in to convert a hash into arrays of (key, value) pairs?
推荐答案
我对此进行了更新。这甚至比console.log更容易解析,因为它省去了那里的额外东西,如 __ proto __
。
I updated this some more. This is much easier to parse than even console.log because it leaves out the extra stuff that's in there like __proto__
.
function flatten(obj) {
var empty = true;
if (obj instanceof Array) {
str = '[';
empty = true;
for (var i=0;i<obj.length;i++) {
empty = false;
str += flatten(obj[i])+', ';
}
return (empty?str:str.slice(0,-2))+']';
} else if (obj instanceof Object) {
str = '{';
empty = true;
for (i in obj) {
empty = false;
str += i+'->'+flatten(obj[i])+', ';
}
return (empty?str:str.slice(0,-2))+'}';
} else {
return obj; // not an obj, don't stringify me
}
}
我唯一要做的就是根据递归级别正确缩进。
The only thing I would do to improve this is have it indent correctly based on recursion level.
这篇关于将对象展平为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文