![](/img/trans.png)
[英]JavaScript: Deconstructing an object with arrays, to an array that has objects
[英]Convert an object to bidimensional Array which has arrays and objects in between (Javascript)
我有一个包含一些信息的数据库,以及一个访问该信息的函数。 但是,使用旧的数据库,我返回了一个完美的二维数组,因此我可以毫无问题地使用它。 现在,有了新的数据库信息,由于某种原因,我将以正确的方式接收一些数据,并以对象的形式接收其他数据:
世界从0变到149,每个都做同样的事情,所以我有
0 0 [1,1,1]
0 1 [1,1,1] etc
但在位置2和47,我有一个对象:
2: {0 [1,1,1] ...
整个想法是将所有内容放入二维数组中:
[[1,1,1],[1,1,1],...],[[1,1,1],[1,1,1],...]
我已经尝试了一些类似Array.from的方法,但是由于它之间存在混合,因此似乎无法转换。
我应该怎么做才能以正确的方式对其进行转换,或者仅访问那些对象,将其转换,然后将每个位置正确的元素添加到二维数组中?
(我试图以最好的方式来解释它……让我知道您是否需要其他帮助来帮助我)
谢谢! ps:该信息来自API
这是我得到的:
世界
Object { 0=[150], 1=[150], 2={...}, más...}
0
[1, 1, 1, 147 más...]
1个
[1, 1, 1, 147 más...]
2
Object { 0=1, 1=1, 2=1, más...}
3
[1, 1, 1, 147 más...]
4
[1, 1, 1, 147 más...]
5
[1, 1, 1, 147 más...]
6
[1, 1, 1, 147 más...]
7
[1, 1, 1, 147 más...]
8
[1, 1, 1, 147 más...]
9
[1, 1, 1, 147 más...]
10
[1, 1, 1, 147 más...]
这就是我需要的:
世界
[[1, 1, 1, 147 más...], [1, 1, 1, 147 más...], [1, 1, 1, 147 más...], 147 más...]
0
[1, 1, 1, 147 más...]
1个
[1, 1, 1, 147 más...]
2
[1, 1, 1, 147 más...]
3
[1, 1, 1, 147 más...]
4
[1, 1, 1, 147 más...]
5
[1, 1, 1, 147 más...]
6
[1, 1, 1, 147 más...]
7
[1, 1, 1, 147 más...]
8
[1, 1, 1, 147 más...]
9
[1, 1, 1, 147 más...]
10
[1, 1, 1, 147 más...]
好了朋友们,
我不确定这是否是最好的方法,但是这是我想到的结果:
var testing = [[]];
var test = [];
var numberOfItems = 0;
for(var item in configs.world){
numberOfItems++;
}
testing.splice(0, testing.length);
for(var i = 0; i < numberOfItems; i++){
console.log(i);
if(Array.isArray(configs.world[i])){
testing.push(configs.world[i]);
} else {
test.splice(0,test.length);
for(var key in configs.world[i]){
var value = configs.world[i][key];
test.push(value);
}
testing.push(test);
}
}
world = testing;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.