Converting a JS object to an array using jQuery

2018-12-31 04:08发布

My application creates a JavaScript object, like the following:

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

But I need this object as an array.

array[1]:[Array-Data]
array[2]:[Array-Data]

So I tried to convert this object to an array by iterating with $.each through the object and adding the element to an array:

x=[]
$.each(myObj, function(i,n) {
    x.push(n);});

Is there an better way to convert an object to an array or maybe a function?

18条回答
十年一品温如言
2楼-- · 2018-12-31 04:42

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]; 
});
查看更多
深知你不懂我心
3楼-- · 2018-12-31 04:43
x = [];
for( var i in myObj ) {
    x[i] = myObj[i];
}
查看更多
初与友歌
4楼-- · 2018-12-31 04:45

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...

查看更多
一个人的天荒地老
5楼-- · 2018-12-31 04:46

Simply do

Object.values(obj);

That's all!

查看更多
弹指情弦暗扣
6楼-- · 2018-12-31 04:47

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)
查看更多
旧人旧事旧时光
7楼-- · 2018-12-31 04:49

ECMASCRIPT 5:

Object.keys(myObj).map(function(x) { return myObj[x]; })

ECMASCRIPT 2015 or ES6:

Object.keys(myObj).map(x => myObj[x])
查看更多
登录 后发表回答