javascript 将值推入多维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16689729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:39:05  来源:igfitidea点击:

Pushing value into a multidimensional array

javascriptarraysmultidimensional-arraypushjavascript-objects

提问by Prasath K

I have surfed the problem but couldn't get any possible solution ..

我已经浏览了这个问题,但找不到任何可能的解决方案..

Let's say i have a var like this

假设我有一个这样的 var

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.lengthand number of keyskeeps changing and i just want to be done using push()without any extra variables. Even i don't want to use extra forloops

注:data.length按键的数量不断变化,我只是想用做push()没有任何额外的变量。即使我不想使用额外的for循环

If you guys found any duplicate here , just put the link as comment without downvote

如果你们在这里发现任何重复,只需将链接作为评论而不是downvote

回答by Slawomir Pasko

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