更好的方式来JS对象转换为数组 [英] a better way to convert JS object to array

查看:222
本文介绍了更好的方式来JS对象转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序创建一个JavaScript对象,如下所示:

  MyObj中= {1:阵列的数据],2:阵列的数据]}

但我需要这个对象的数组。

 数组[1]:[阵列的数据]
数组[2]:[阵列的数据]

所以,我试图用 $迭代这个对象转换为数组中的每个通过对象,并添加元素的数组:

  X = []
$。每个(MyObj中,函数(I,N){
    x.push(正);});

是否有更好的方法来将对象转换为一个数组或者一个功能,我不知道?!?

感谢您。


解决方案

  VAR MyObj中= {
    1:[1,2,3]
    2:[4,5,6]
};VAR阵列= $ .MAP(MyObj中,功能(价值指数){
    返回[值];
});
的console.log(数组);

输出:

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

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 an function, I don't know?!?

Thank you.

解决方案

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

这篇关于更好的方式来JS对象转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆