在对象创建中运行循环

时间:2017-09-21 19:49:42

标签: javascript loops

我知道这完全错了,但我被困住了。

我有一组对象。

从此我想创建3个对象。

创建的第一个对象我需要一个在原始对象中包含所有'uppVal'值的数组。

创建的第二个对象需要'midVal'值,第三个对象需要'lowval'值

我知道这是错的

outputData.push({
    dataNum: []
    for (var n = 0; n < data.length; n++) {
      dataNum.push(data[n][key])
    }
  })

但我正在尝试在创建对象时获取值

var outputData = [];

data = [{
    "uppVal": 68,
    "midVal": 34,
    "lowVal": 4,
  },
  {
    "uppVal": 68,
    "midVal": 34,
    "lowVal": 4,
  },
  {
    "uppVal": 68,
    "midVal": 34,
    "lowVal": 4,
  },
  {
    "uppVal": 68,
    "midVal": 34,
    "lowVal": 4,
  },
  {
    "uppVal": 68,
    "midVal": 34,
    "lowVal": 4,
  },
  {
    "uppVal": 68,
    "midVal": 34,
    "lowVal": 4,
  }
]

titlesArr = ['uppVal', 'midVal', 'lowVal']

for (var i = 0; i < 3; i++) {
  var counter = 0
  var key = titlesArr[counter]
  outputData.push({
    dataNum: []
    for (var n = 0; n < data.length; n++) {
      dataNum.push(data[n][key])
    }
  })
  counter++
}

console.log(outputData);

2 个答案:

答案 0 :(得分:1)

您可以迭代给定的数据和键数组,并使用键的索引对结果集进行处理。

&#13;
&#13;
var data = [{ uppVal: 68, midVal: 34, lowVal: 4 }, { uppVal: 68, midVal: 34, lowVal: 4 }, { uppVal: 68, midVal: 34, lowVal: 4 }, { uppVal: 68, midVal: 34, lowVal: 4 }, { uppVal: 68, midVal: 34, lowVal: 4 }, { uppVal: 68, midVal: 34, lowVal: 4 }],
    result = [[], [], []];

data.forEach(function (o) {
    ['uppVal', 'midVal', 'lowVal'].forEach(function (k, i) {
        result[i].push(o[k]);
    });
});

console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:1)

所以你基本上想要将data[index][key]切换为outputData[key][index]

data = [ { "uppVal": 68, "midVal": 34, "lowVal": 4 },
         { "uppVal": 68, "midVal": 34, "lowVal": 4 },
         { "uppVal": 68, "midVal": 34, "lowVal": 4 },
         { "uppVal": 68, "midVal": 34, "lowVal": 4 },
         { "uppVal": 68, "midVal": 34, "lowVal": 4 },
         { "uppVal": 68, "midVal": 34, "lowVal": 4 } ]
         
outputData = { uppVal: [], midVal: [], lowVal: [] }

for (var i = 0; i < data.length; i++) 
{
    outputData.uppVal[i] = data[i].uppVal
    outputData.midVal[i] = data[i].midVal
    outputData.lowVal[i] = data[i].lowVal
}

console.log(outputData)