我的应用程序创建了一个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);});

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


当前回答

小提琴演示

引申到比约德的答案。

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

种()

其他回答

如果您希望将对象属性的名称保留为值。例子:

var fields = {
    Name: { type: 'string', maxLength: 50 },
    Age: { type: 'number', minValue: 0 }
}

使用Object.keys(), Array.map()和Object.assign():

var columns = Object.keys( fields ).map( p => Object.assign( fields[p], {field:p} ) )

结果:

[ { field: 'Name', type: 'string', maxLength: 50 }, 
  { field: 'Age', type: 'number', minValue: 0 } ]

解释:

Object.keys()枚举源的所有属性;.map()对每个属性应用=>函数并返回Array;Object.assign()合并每个属性的名称和值。

我认为你可以使用for,但检查是否财产不是继承的

myObj= {1:[Array-Data], 2:[Array-Data]}
var arr =[];
for( var i in myObj ) {
    if (myObj.hasOwnProperty(i)){
       arr.push(myObj[i]);
    }
}

编辑-如果你想要,你也可以保留对象的索引,但你必须检查它们是否为数字(并且你会得到未定义的缺失索引值:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

myObj= {1:[1,2], 2:[3,4]}
var arr =[];
for( var i in myObj ) {
    if (myObj.hasOwnProperty(i)){
        if (isNumber(i)){
            arr[i] = myObj[i];
        }else{
          arr.push(myObj[i]);
        }
    }
}
x = [];
for( var i in myObj ) {
    x[i] = myObj[i];
}

小提琴演示

引申到比约德的答案。

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

种()

我做了一个自定义函数:

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