使用jQuery將JS對象轉換爲數組

本文翻譯自:Converting a JS object to an array using jQuery

My application creates a JavaScript object, like the following: 我的應用程序創建了一個JavaScript對象,如下所示:

myObj= {1:[Array-Data], 2:[Array-Data]}

But I need this object as an array. 但是我需要將此對象作爲數組。

array[1]:[Array-Data]
array[2]:[Array-Data]

So I tried to convert this object to an array by iterating with $.each through the object and adding the element to an array: 所以我嘗試通過$.each遍歷對象並將元素添加到數組中來將該對象轉換爲數組:

x=[]
$.each(myObj, function(i,n) {
    x.push(n);});

Is there an better way to convert an object to an array or maybe a function? 有沒有更好的方法將對象轉換爲數組或函數?


#1樓

參考:https://stackoom.com/question/SlwK/使用jQuery將JS對象轉換爲數組


#2樓

Fiddle Demo 小提琴演示

Extension to answer of bjornd . 比約德答案的擴展

var myObj = {
    1: [1, [2], 3],
    2: [4, 5, [6]]
}, count = 0,
    i;
//count the JavaScript object length supporting IE < 9 also
for (i in myObj) {
    if (myObj.hasOwnProperty(i)) {
        count++;
    }
}
//count = Object.keys(myObj).length;// but not support IE < 9
myObj.length = count + 1; //max index + 1
myArr = Array.prototype.slice.apply(myObj);
console.log(myArr);


Reference 參考

Array.prototype.slice() Array.prototype.slice()

Function.prototype.apply() Function.prototype.apply()

Object.prototype.hasOwnProperty() Object.prototype.hasOwnProperty()

Object.keys() Object.keys()


#3樓

How about jQuery.makeArray(obj) jQuery.makeArray(obj)怎麼樣

This is how I did it in my app. 這就是我在應用程序中所做的事情。


#4樓

I made a custom function: 我做了一個自定義函數:

    Object.prototype.toArray=function(){
    var arr=new Array();
    for( var i in this ) {
        if (this.hasOwnProperty(i)){
            arr.push(this[i]);
        }
    }
    return arr;
};

#5樓

最好的方法是使用僅javascript函數:

var myArr = Array.prototype.slice.call(myObj, 0);

#6樓

If you are looking for a functional approach: 如果您正在尋找一種實用的方法:

var obj = {1: 11, 2: 22};
var arr = Object.keys(obj).map(function (key) { return obj[key]; });

Results in: 結果是:

[11, 22]

The same with an ES6 arrow function: 與ES6箭頭功能相同:

Object.keys(obj).map(key => obj[key])

With ES7 you will be able to use Object.values instead ( more information ): 使用ES7,您將可以改爲使用Object.values更多信息 ):

var arr = Object.values(obj);

Or if you are already using Underscore/Lo-Dash: 或者,如果您已經在使用Underscore / Lo-Dash:

var arr = _.values(obj)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章