我想生成JSON数组,如下所示。
完全详细的数组;
MyArray = [{ prj : "P1", days : "8", ot : "2" }, { prj : "P2", days : "8", ot : "2" }, { prj : "P2", days : "8", ot : "2" }, { prj : "P1", days : "8", ot : "2" }{prj : "P3", days : "8", ot : "2" }, { prj : "P2", days : "8", ot : "2" }, { prj : "P3", days : "8", ot : "2" }];
但我想按如下方式压缩它;
MyArray = [{ prj : "P1", days : "16", ot : "4" }, { prj : "P2", days : "24", ot : "6" }, { prj : "P3", days : "16", ot : "4" }];
如果存在project_number,它应该得到天数和OT;
答案 0 :(得分:1)
试试这个,这符合你的需要。
var MyArray = [];
//This will be used to construct your JSON object
function ConstructJson(prj, days, ot) {
var xObj = {};
xObj.prj = prj;
xObj.days = days;
xObj.ot = ot;
MyArray[MyArray.length] = xObj;
}
//This will minimise your json object.
function MinimiseJson() {
var xTempArray = [];
var xTempObj = {};
var xPrj = '';
for (var i = 0; i < MyArray.length; i++) {
if (xPrj == '' && MyArray[i]) {
xPrj = MyArray[i].prj;
xTempObj.prj = xPrj;
xTempObj.days = MyArray[i].days;
xTempObj.ot = MyArray[i].ot;
for (var j = i + 1; j < MyArray.length; j++) {
if (MyArray[j] && MyArray[j].prj == xPrj) {
xTempObj.days += MyArray[j].days;
xTempObj.ot += MyArray[j].ot;
MyArray[j] = null;
}
}
xPrj = '';
xTempArray[xTempArray.length] = xTempObj;
xTempObj = {};
}
}
return xTempArray;
}
答案 1 :(得分:1)
一个非常简单的解决方案就是遍历所有日子,并在您经历时跟踪值的总和。我按如下方式分叉你的jsfiddle:http://jsfiddle.net/BM9VE/,这是JS:
$(function () {
var proj, score, MyArray = [], tally = {};
for (var i = 1; i <= 7; i++) {
proj = $('#p' + i).val();
score = tally[proj] || {prj: proj, days: 0, ot: 0}; // default val if we haven't seen this day yet
score.days += parseInt($('#d' + i).val());
score.ot += parseInt($('#ot' + i).val());
tally[proj] = score;
}
for (var day in tally) {
// your example has days and ot as strings, this code keeps them as numbers; feel free to convert them back into strings if you need to, here
MyArray.push(tally[day]);
}
$('body').append('<p>MyArray: ' + JSON.stringify(MyArray) + '</p>');
});