我的应用程序创建了一个JavaScript对象,如下所示:

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

但我需要这个对象作为数组。

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

因此,我尝试通过$迭代将该对象转换为数组。遍历对象并将元素添加到数组:

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

是否有更好的方法将对象转换为数组或函数?


当前回答

现在,有一种简单的方法可以做到这一点:Object.values()。

var myObj = {
    1: [1, 2, 3],
    2: [4, 5, 6]
};

console.log(Object.values(myObj));

输出:

[[1, 2, 3], [4, 5, 6]]

这并不需要jQuery,它已经在ECMAScript 2017中定义了。 每个现代浏览器都支持它(忘了IE吧)。

其他回答

因为ES5 object .keys()返回一个数组,其中包含直接在对象上定义的属性(不包括在原型链中定义的属性):

Object.keys(yourObject).map(function(key){ return yourObject[key] });

ES6在箭头函数方面更进一步:

Object.keys(yourObject).map(key => yourObject[key]);

小提琴演示

引申到比约德的答案。

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 ()

Function.prototype.apply ()

Object.prototype.hasOwnProperty ()

种()

最好的方法是使用javascript独有的函数:

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

如果你知道对象的最大索引,你可以这样做:

var myObj = { 1: ['c', 'd'], 2: ['a', 'b'] }, myArr; myObj。长度= 3;//max index + 1 myArr = Array.prototype.slice.apply(myObj); console.log (myArr);//[undefined, ['c', 'd'], ['a', 'b']]

var myObj = {
    1: [1, 2, 3],
    2: [4, 5, 6]
};

var array = $.map(myObj, function(value, index) {
    return [value];
});


console.log(array);

输出:

[[1, 2, 3], [4, 5, 6]]