Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten object to array?

Tags:

javascript

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?

like image 436
Steven Lu Avatar asked Oct 05 '11 11:10

Steven Lu


3 Answers

Since you want to alert it out I assume it's not for your production version, and that old browser compatibility is not an issue.

If this is the case, then you can do this:

var myHash = ......
alert(Object.keys(myHash).map(function(key) { return [key, myHash[key]]; }));
like image 167
megakorre Avatar answered Oct 03 '22 07:10

megakorre


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.

like image 31
Steven Lu Avatar answered Oct 03 '22 08:10

Steven Lu


for quick & dirty use in alert you could use JSON:

alert(JSON.stringify(yourObj).replace(/,/g,'\n'));
like image 29
KooiInc Avatar answered Oct 03 '22 08:10

KooiInc