Flatten object to array?

前端 未结 7 1221
佛祖请我去吃肉
佛祖请我去吃肉 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:44

    Not that I'm aware of. Still, you can do it yourself fairly concisely:

    var obj = { a: 1, b: 2, c: 3 };
    var arr = [];
    for (var i in obj) {
       var e = {};
       e[i] = obj[i];
       arr.push(e);
    }
    console.log(arr);
    // Output: [Object { a=1 }, Object { b=2 }, Object { c=3 }]
    

    Of course, you can't alert this either, so you might as well just console.log(obj) in the first place.


    You could output arrays of arrays:

    var obj = { a: 1, b: 2, c: 3 };
    var arr = [];
    for (var i in obj) {
       arr.push([i, obj[i]]);
    }
    console.log(arr);
    // Output: [["a", 1], ["b", 2], ["c", 3]]
    
    alert(arr);
    // Alert: a, 1, b, 2, c, 3
    

    But, again, ew.

提交回复
热议问题