我想以下面的方式生成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,则应得到天数之和;
见示例
发布于 2013-12-01 06:29:36
试试这个,这个适合你的需要。
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;
}现场演示
发布于 2013-12-01 06:59:54
一个非常简单的解决方案就是循环遍历所有的日子,并跟踪您所经历的值的总和。我把你的小提琴曲分叉如下: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>');
});https://stackoverflow.com/questions/20309369
复制相似问题