Converting a JS object to an array using jQuery

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

提交回复
热议问题