【发布时间】:2018-05-03 12:35:07
【问题描述】:
鉴于我的核心数据如下:
var data = [
{ name: "Student01", type: "received", grades: [ 12,12, 17, 17, 14.5, 10, 16, 15.5, 15.5, 15 ] },
{ name: "Student02", type: "given", grades: [ 11,6,15, 12 ] },
{ name: "Student03", type: "received", grades: [ 12,12, 17, 17, 14.5, 10, 16, 15.5, 15.5, 15 ] },
{ name: "Student04", type: "given", grades: [ 12,8,13, 12 ] }
];
给定一个我应该尊重的模板对象:
var template = {
text: "Hello guys !",
side: "negative",
name: "Some student",
x: [ 12.65, 17.92, 16.45 ],
orientation: "h"
};
然后我通过 for 循环构建一个 augmentedData:
var augmentedData = [];
for (var i=0; i<data.length;i++){
var trace = template,
student = data[i];
trace.text = "Step "+i;
trace.name = student.name;
trace.x = student.grades;
console.log(student, student.type)
trace.side = student.type == "given"?"negative":"positive";
console.log(vizGrades[i].type, trace, trace.side)
augmentedData.push(trace);
}
我的最终增强数据由最后一个对象的 4 倍组成,本身就是增强的:
console.log(JSON.stringify(augmentedData));
返回:
[
{"text":"Step 3","side":"negative","name":"Student04","x":[12,8,13,12],"orientation":"h"},
{"text":"Step 3","side":"negative","name":"Student04","x":[12,8,13,12],"orientation":"h"},
{"text":"Step 3","side":"negative","name":"Student04","x":[12,8,13,12],"orientation":"h"},
{"text":"Step 3","side":"negative","name":"Student04","x":[12,8,13,12],"orientation":"h"}
];
出了什么问题?如何解决?
编辑:预期输出:
[
{"text":"Step 0","side":"positive","name":"Student01","x":[12,12, 17, 17, 14.5, 10, 16, 15.5, 15.5, 15],"orientation":"h"},
{"text":"Step 1","side":"negative","name":"Student02","x":[11,6,15, 12],"orientation":"h"},
{"text":"Step 2","side":"positive","name":"Student03","x":[12,12, 17, 17, 14.5, 10, 16, 15.5, 15.5, 15],"orientation":"h"},
{"text":"Step 3","side":"negative","name":"Student04","x":[12,8,13,12],"orientation":"h"}
];
【问题讨论】:
-
你的预期输出是多少?
标签: javascript arrays for-loop