JavaScript, transform object into array

前端 未结 9 1917
孤城傲影
孤城傲影 2020-12-14 15:58

I\'ve got an object:

var obj = {
    \"Mike\": 24,
    \"Peter\": 23,
    \"Simon\": 33,
    \"Tom\": 12,
    \"Frank\": 31
};

I want to cr

相关标签:
9条回答
  • 2020-12-14 16:36

    There's no built-in way to do this anywhere. The following does what you suggest, and may be "shortened" into more clever functional-programming versions depending on your library, but they'll all have the same efficiency.

    function valuesToArray(obj) {
        var result = [];
        for (var key in obj) {
           if (obj.hasOwnProperty(key)) {
               result.push(obj[key]);
           }
        }
        return result;
    }
    
    0 讨论(0)
  • 2020-12-14 16:39

    Using the Underscore lib try:

    function valuesToArray(o) {
        return _.pairs(o);
    }
    
    var obj = {
        "Mike": 24,
        "Peter": 23
        //...
        },
        result = valuesToArray(obj);
    

    Then the result is [ ["Mike", 24], ["Peter", 23] ];

    More detail on the pairs method here: http://underscorejs.org/#pairs

    0 讨论(0)
  • 2020-12-14 16:40

    Using bob.js this can be done pretty simply:

    function valuesToArray(obj) {
        return bob.collections.extensions.toArray.call(obj);
    }
    
    0 讨论(0)
提交回复
热议问题