所以我的数组看起来像这样:
var data = ["5/10/2014", 2, "5/10/2014", 5, "5/11/2014", 6....];
阵列有超过数千个细胞,这无关紧要,但无论如何我都会提到它。
我想将该数组转换为如下所示的对象数组:
var iWantToBelieve = [{Date:"5/10/2014", Score: 2}, {Date: 5/10/2014, Score:5}.....];
我觉得我已接近解决问题,但我的代码给了我最终结果:
var iWantToBelieve = [{Date:"5/10/2014", Score: "5/10/2014"}, {Date: 5/10/2014, Score: "5/10/2014"}.....]
我的代码如下所示:
var data = ["5/10/2014", 2, "5/10/2014", 5, "5/11/2014", 6....];
var init = [];
var tempObject;
for(var z = 0; z < data.length; z++){
var tempArray = ["Date", "Score"];
tempObject = {};
for(var y = 0; y < tempArray.length; y++){
tempObject[tempArray[y]] = data[z];
}
init.push(tempObject);
}
我知道第二个for循环在第一个循环开始另一次迭代之前完成了2次迭代,因此Date和Score键都被日期字符串占用。
感谢任何帮助。
答案 0 :(得分:5)
您可以使用并将itterator增加2。
var iWantToBelieve = []
for (var i = 0; i < data.length; i += 2) { // i = 0, 2, 4..
iWantToBelieve.push({
Date: data[i], // 1st value is the date
Score: data[i + 1] // 2nd value is score
});
}
答案 1 :(得分:0)
var data = ["5/10/2014", 2, "5/10/2014", 5, "5/11/2014", 6]
var result = []
for (var j=0; j<data.length; j+=2)
result.push({ Date: data[j], Score: data[j + 1]})
console.log(result)
答案 2 :(得分:0)
var data = ["5/10/2014", 2, "5/10/2014", 5, "5/11/2014", 6];
var result = [];
while (data.length) result.push({Date: data.shift(), Score: data.shift()});
console.log(result);