Converting a JS object to an array using jQuery

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

    ES8 way made easy:

    The official documentation

        const obj = { x: 'xxx', y: 1 };
        let arr = Object.values(obj); // ['xxx', 1]
        console.log(arr);

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

    The solving is very simple

    var my_obj = {1:[Array-Data], 2:[Array-Data]}
    Object.keys(my_obj).map(function(property_name){ 
        return my_obj[property_name]; 
    });
    
    0 讨论(0)
  • 2020-11-22 02:12

    I made a custom function:

        Object.prototype.toArray=function(){
        var arr=new Array();
        for( var i in this ) {
            if (this.hasOwnProperty(i)){
                arr.push(this[i]);
            }
        }
        return arr;
    };
    
    0 讨论(0)
  • 2020-11-22 02:13
    x = [];
    for( var i in myObj ) {
        x[i] = myObj[i];
    }
    
    0 讨论(0)
  • 2020-11-22 02:13

    You can create a simple function to do the conversion from object to array, something like this can do the job for you using pure 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;
    };
    

    or this one:

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

    and call and use the function as below:

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

    Also in the future we will have something called Object.values(obj), similar to Object.keys(obj) which will return all properties for you as an array, but not supported in many browsers yet...

    0 讨论(0)
  • 2020-11-22 02:17
    var myObj = {
        1: [1, 2, 3],
        2: [4, 5, 6]
    };
    
    var array = $.map(myObj, function(value, index) {
        return [value];
    });
    
    
    console.log(array);
    

    Output:

    [[1, 2, 3], [4, 5, 6]]
    
    0 讨论(0)
提交回复
热议问题