Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
104
rated 0 times [  105] [ 1]  / answers: 1 / hits: 21281  / 13 Years ago, wed, october 5, 2011, 12:00:00

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?


More From » javascript

 Answers
51

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.


[#89782] Monday, October 3, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jordenfabiand

Total Points: 678
Total Questions: 107
Total Answers: 95

Location: Western Sahara
Member since Mon, May 3, 2021
3 Years ago
;