简体   繁体   English

使用jQuery将JS对象转换为数组

[英]Converting a JS object to an array using jQuery

My application creates a JavaScript object, like the following: 我的应用程序创建了一个JavaScript对象,如下所示:

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: 所以我尝试通过$.each遍历对象并将元素添加到数组中来将该对象转换为数组:

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? 有没有更好的方法将对象转换为数组或函数?

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: 与ES6箭头功能相同:

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

With ES7 you will be able to use Object.values instead ( more information ): 使用ES7,您将可以改为使用Object.values更多信息 ):

var arr = Object.values(obj);

Or if you are already using Underscore/Lo-Dash: 或者,如果您已经在使用Underscore / Lo-Dash:

var arr = _.values(obj)
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]]

I think you can use for in but checking if the property is not inerithed 我认为您可以使用for in但请检查属性是否未惯用

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

Simply do 简单地做

Object.values(obj);

That's all! 就这样!

If you know the maximum index in you object you can do the following: 如果知道对象中的最大索引,则可以执行以下操作:

 var myObj = { 1: ['c', 'd'], 2: ['a', 'b'] }, myArr; myObj.length = 3; //max index + 1 myArr = Array.prototype.slice.apply(myObj); console.log(myArr); //[undefined, ['c', 'd'], ['a', 'b']] 

Since ES5 Object.keys() returns an array containing the properties defined directly on an object (excluding properties defined in the prototype chain): 由于ES5 Object.keys()返回一个数组,其中包含直接在对象上定义的属性(不包括原型链中定义的属性):

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

ES6 takes it one step further with arrow functions: ES6借助箭头功能进一步迈出了一步:

Object.keys(yourObject).map(key => yourObject[key]);

Nowadays, there is a simple way to do this : Object.values() . 如今,有一种简单的方法可以执行此操作: 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. 不需要jQuery,它已在ECMAScript 2017中定义。
It's supported by every modern browser (forget IE). 每个现代浏览器(忘记IE)都支持它。

最好的方法是使用仅javascript函数:

var myArr = Array.prototype.slice.call(myObj, 0);

ECMASCRIPT 5: ECMASCRIPT 5:

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

ECMASCRIPT 2015 or ES6: ECMASCRIPT 2015或ES6:

Object.keys(myObj).map(x => myObj[x])
x = [];
for( var i in myObj ) {
    x[i] = myObj[i];
}

How about jQuery.makeArray(obj) jQuery.makeArray(obj)怎么样

This is how I did it in my app. 这就是我在应用程序中所做的事情。

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

ES8 way made easy : ES8的方法 变得简单

The official documentation 官方文件

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

Fiddle Demo 小提琴演示

Extension to answer of bjornd . 比约德答案的扩展

var myObj = {
    1: [1, [2], 3],
    2: [4, 5, [6]]
}, count = 0,
    i;
//count the JavaScript object length supporting IE < 9 also
for (i in myObj) {
    if (myObj.hasOwnProperty(i)) {
        count++;
    }
}
//count = Object.keys(myObj).length;// but not support IE < 9
myObj.length = count + 1; //max index + 1
myArr = Array.prototype.slice.apply(myObj);
console.log(myArr);


Reference 参考

Array.prototype.slice() Array.prototype.slice()

Function.prototype.apply() Function.prototype.apply()

Object.prototype.hasOwnProperty() Object.prototype.hasOwnProperty()

Object.keys() Object.keys()

If you want to keep the name of the object's properties as values. 如果要保留对象属性的名称作为值。 Example: 例:

var fields = {
    Name: { type: 'string', maxLength: 50 },
    Age: { type: 'number', minValue: 0 }
}

Use Object.keys() , Array.map() and Object.assign() : 使用Object.keys()Array.map()Object.assign()

var columns = Object.keys( fields ).map( p => Object.assign( fields[p], {field:p} ) )

Result: 结果:

[ { field: 'Name', type: 'string', maxLength: 50 }, 
  { field: 'Age', type: 'number', minValue: 0 } ]

Explanation: 说明:

Object.keys() enumerates all the properties of the source ; Object.keys()枚举源的所有属性; .map() applies the => function to each property and returns an Array ; .map()=>函数应用于每个属性并返回Array; Object.assign() merges name and value for each property. Object.assign()合并每个属性的名称和值。

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

After some tests, here is a general object to array function convertor: 经过一些测试,这是数组函数转换器的通用对象:

You have the object: 您有对象:

var obj = {
    some_key_1: "some_value_1"
    some_key_2: "some_value_2"
};

The function: 功能:

function ObjectToArray(o)
{
    var k = Object.getOwnPropertyNames(o);
    var v = Object.values(o);

    var c = function(l)
    {
        this.k = [];
        this.v = [];
        this.length = l;
    };

    var r = new c(k.length);

    for (var i = 0; i < k.length; i++)
    {
        r.k[i] = k[i];
        r.v[i] = v[i];
    }

    return r;
}

Function Use: 功能用途:

var arr = ObjectToArray(obj);

You Get: 你得到:

 arr { key: [ "some_key_1", "some_key_2" ], value: [ "some_value_1", "some_value_2" ], length: 2 } 

So then you can reach all keys & values like: 这样您就可以达到所有键和值,例如:

for (var i = 0; i < arr.length; i++)
{
    console.log(arr.key[i] + " = " + arr.value[i]);
}

Result in console: 结果在控制台中:

 some_key_1 = some_value_1 some_key_2 = some_value_2 

Edit: 编辑:

Or in prototype form: 或以原型形式:

Object.prototype.objectToArray = function()
{
    if (
        typeof this != 'object' ||
        typeof this.length != "undefined"
    ) {
        return false;
    }

    var k = Object.getOwnPropertyNames(this);
    var v = Object.values(this);

    var c = function(l)
    {
        this.k = [];
        this.v = [];
        this.length = l;
    };

    var r = new c(k.length);

    for (var i = 0; i < k.length; i++)
    {
        r.k[i] = k[i];
        r.v[i] = v[i];
    }

    return r;
};

And then use like: 然后像这样使用:

console.log(obj.objectToArray);

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: 您可以创建一个简单的函数来完成从objectarray的转换,像这样的事情可以使用纯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... 同样在将来,我们将有一个叫做Object.values(obj)东西,类似于Object.keys(obj) ,它将为您返回所有属性作为数组,但在许多浏览器中尚不支持...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM