按顺序将数组推入数组(带地图)

时间:2018-03-29 12:03:58

标签: javascript arrays

我有一个成功映射的数组,创建新数组。现在我想创建一个包含所有较小数组的主设备。我知道你可以推进它。但是有更好的(更少的代码)方法吗?

这是我的代码:

 obj = {
      data: [ 
        {
          temp: 1,
          air: 2,
          cloud: 3
        },
        {
          temp: 100,
          air: 101,
          cloud: 102
        }
      ]
    };
    
/*
    var temp = obj.data.map(a => a.temp); // middle step
    var air = obj.data.map(a => a.air); // middle step
        
    var OneArrayToRuleThemAll = [];
    OneArrayToRuleThemAll.push(temp,air);
    
    console.log(OneArrayToRuleThemAll);
*/

// It may be easier for you to understand, when I simply comment out half of the // code and get straight to expected result.

预期结果:包含以下内容的新数组:

[
  [
    1,
    100
  ],
  [
    2,
    101
  ]
]

换句话说:我可以以某种方式映射/循环主obj和创建OneArrayToRuleThemAll而无需中间步骤吗?

我的预期结果应该与OneArrayToRuleThemAll相同 - 没有中间步骤。

谢谢

2 个答案:

答案 0 :(得分:0)

  var temp = []
  var air = []
  var OneArrayToRuleThemAll = []
  var length = obj.data.length
  var count = 0
  obj.data.map( (o) => {
    count ++
    temp.push(o.temp)
    air.push(o.air)
    if (count == length){
      OneArrayToRuleThemAll.push(temp, air)
    }
  })

答案 1 :(得分:0)

您可以使用数组作为键,并将数组转换为所需的样式。



.as-console-wrapper { max-height: 100% !important; top: 0; }

console.log("- Vector -");
var v = new ActiveXObject('WIA.Vector');
v.SetFromString('This is a test', true, false);
for (var i = 1; i<= v.Count; i++) {
    console.log(v(i), String.fromCharCode(v(i)), typeof v(i));
}

console.log("- Enumerator -");
var e = new Enumerator(v);
e.moveFirst();
while (!e.atEnd()) {
    console.log(e.item(), String.fromCharCode(e.item()), typeof e.item());
    e.moveNext(); // You need this
}
&#13;
&#13;
&#13;