Converting a JS object to an array using jQuery

后端 未结 18 3367
鱼传尺愫
鱼传尺愫 2020-11-22 01:37

My application creates a JavaScript object, like the following:

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

But I need this object as an array.

18条回答
  •  执笔经年
    2020-11-22 02:05

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

    Function.prototype.apply()

    Object.prototype.hasOwnProperty()

    Object.keys()

提交回复
热议问题