Flatten object to array?

前端 未结 7 1263
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-05 03:21

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

7条回答
  •  耶瑟儿~
    2021-01-05 03: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'+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.

提交回复
热议问题