Converting a JS object to an array using jQuery

后端 未结 18 3091
鱼传尺愫
鱼传尺愫 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:02

    I think you can use for in but checking if the property is not inerithed

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

    EDIT - if you want you could also keep the indexes of your object, but you have to check if they are numeric (and you get undefined values for missing indexes:

    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]);
            }
        }
    }
    

提交回复
热议问题