Converting a JS object to an array using jQuery

后端 未结 18 3053
鱼传尺愫
鱼传尺愫 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 01:55

    How about jQuery.makeArray(obj)

    This is how I did it in my app.

    0 讨论(0)
  • 2020-11-22 01:56

    Nowadays, there is a simple way to do this : Object.values().

    var myObj = {
        1: [1, 2, 3],
        2: [4, 5, 6]
    };
    
    console.log(Object.values(myObj));
    

    Output:

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

    This doesn't required jQuery, it's been defined in ECMAScript 2017.
    It's supported by every modern browser (forget IE).

    0 讨论(0)
  • 2020-11-22 02:00

    The best method would be using a javascript -only function:

    var myArr = Array.prototype.slice.call(myObj, 0);
    
    0 讨论(0)
  • 2020-11-22 02:02

    If you are looking for a functional approach:

    var obj = {1: 11, 2: 22};
    var arr = Object.keys(obj).map(function (key) { return obj[key]; });
    

    Results in:

    [11, 22]
    

    The same with an ES6 arrow function:

    Object.keys(obj).map(key => obj[key])
    

    With ES7 you will be able to use Object.values instead (more information):

    var arr = Object.values(obj);
    

    Or if you are already using Underscore/Lo-Dash:

    var arr = _.values(obj)
    
    0 讨论(0)
  • 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]);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 02:02

    Since ES5 Object.keys() returns an array containing the properties defined directly on an object (excluding properties defined in the prototype chain):

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

    ES6 takes it one step further with arrow functions:

    Object.keys(yourObject).map(key => yourObject[key]);
    
    0 讨论(0)
提交回复
热议问题