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

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


console.log(array);

输出:

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

其他回答

小提琴演示

引申到比约德的答案。

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

种()

x = [];
for( var i in myObj ) {
    x[i] = myObj[i];
}

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

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

你可以创建一个简单的函数来完成从对象到数组的转换,像这样的东西可以为你使用纯javascript完成工作:

var objectToArray = function(obj) {
  var arr = [];
  if ('object' !== typeof obj || 'undefined' === typeof obj || Array.isArray(obj)) {
    return obj;
  } else {
    Object.keys(obj).map(x=>arr.push(obj[x]));
  }
  return arr;
};

或者这个:

var objectToArray = function(obj) {
  var arr =[];
  for(let o in obj) {
    if (obj.hasOwnProperty(o)) {
      arr.push(obj[o]);
    }
  }
  return arr;
};

调用并使用函数,如下所示:

var obj = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'};
objectToArray(obj); // return ["a", "b", "c", "d", "e"]

另外,在未来我们还会有一些叫做Object.values(obj)的东西,类似于Object.keys(obj),它会以数组的形式为你返回所有属性,但在许多浏览器中还不支持…

ECMASCRIPT 5:

Object.keys(myObj).map(function(x) { return myObj[x]; })

2015年或ES6:

Object.keys(myObj).map(x => myObj[x])