简体   繁体   English

将值推入多维数组

[英]Pushing value into a multidimensional array

I have surfed the problem but couldn't get any possible solution .. 我已经解决了这个问题,但无法获得任何可能的解决方案..

Let's say i have a var like this 假设我有一个像这样的变量

var data = [
           {
              'a':10,
              'b':20,
              'c':30
           },
           {
              'a':1,
              'b':2,
              'c':3
           },
           {
              'a':100,
              'b':200,
              'c':300
           }];

Now , i need a multidimensional array like 现在,我需要一个多维数组

var values = [[10,1,100],    //a
              [20,2,200],    //b
              [30,3,300]];   //c

What i have tried is 我试过的是

var values = [];
for(var key in data[0])
{
   values.push([]);   // this creates a multidimesional array for each key
   for(var i=0;i<data.length;i++)
   {
     // how to push data[i][key] in the multi dimensional array
   }
}

Note : data.length and number of keys keeps changing and i just want to be done using push() without any extra variables. 注意: data.length键的数量不断变化,我只想使用push()而不需要任何额外的变量。 Even i don't want to use extra for loops 即使我不想使用额外的for循环

If you guys found any duplicate here , just put the link as comment without downvote 如果你们在这里发现任何重复,只需将链接作为评论而不用downvote

Try this: 尝试这个:

var result = new Array();

for(var i = 0; i < data.length; i++) {
  var arr = new Array();
  for(var key in data[i]) {
    arr.push(data[i][key]);
  }
  result.push(arr);
}

also if you don't want the 'arr' variable just write directly to the result, but in my opinion code above is much more understandable: 如果您不希望'arr'变量直接写入结果,但在我看来,上面的代码更容易理解:

for(var i = 0; i < data.length; i++) {
  result.push(new Array());
  for(var key in data[i]) {
    result[i].push(data[i][key]);
  }
}

Ok, based on your comment I have modified the the loop. 好的,根据你的评论,我修改了循环。 Please check the solution and mark question as answered if it is what you need. 如果您需要,请检查解决方案并将问题标记为已回答。 Personally I don't understand why you prefer messy and hard to understand code instead of using additional variables, but that's totally different topic. 就个人而言,我不明白你为什么喜欢凌乱而难以理解的代码,而不是使用额外的变量,但这是完全不同的主题。

for(var i = 0; i < data.length; i++) {
  for(var j = 0; j < Object.keys(data[0]).length; j++) {
    result[j] = result[j] || new Array();
    console.log('result[' + j + '][' + i + ']' + ' = ' + data[i][Object.keys(data[i])[j]])
    result[j][i] = data[i][Object.keys(data[i])[j]];
  }
}

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

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