JavaScript, transform object into array

前端 未结 9 1949
孤城傲影
孤城傲影 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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;
    }
    

提交回复
热议问题