本文翻译自: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? 有没有更好的方法将对象转换为数组或函数?
参考:https://stackoom.com/question/SlwK/使用jQuery将JS对象转换为数组
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);
Array.prototype.slice() Array.prototype.slice()
Function.prototype.apply() Function.prototype.apply()
Object.prototype.hasOwnProperty() Object.prototype.hasOwnProperty()
How about jQuery.makeArray(obj)
jQuery.makeArray(obj)
怎么样
This is how I did it in my app. 这就是我在应用程序中所做的事情。
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;
};
最好的方法是使用仅javascript函数:
var myArr = Array.prototype.slice.call(myObj, 0);
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)