首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用天和OT和project_no创建数组

使用天和OT和project_no创建数组
EN

Stack Overflow用户
提问于 2013-12-01 06:22:23
回答 2查看 55关注 0票数 2

我想以下面的方式生成JSON数组。

充分详细的阵列;

代码语言:javascript
复制
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" }];

但我想把它压缩如下;

代码语言:javascript
复制
MyArray = [{ prj : "P1", days : "16", ot : "4" }, { prj : "P2", days : "24", ot : "6" }, { prj : "P3", days : "16", ot : "4" }];

如果存在project_number,则应得到天数之和;

见示例

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-12-01 06:29:36

试试这个,这个适合你的需要。

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2013-12-01 06:59:54

一个非常简单的解决方案就是循环遍历所有的日子,并跟踪您所经历的值的总和。我把你的小提琴曲分叉如下:http://jsfiddle.net/BM9VE/,这是JS:

代码语言:javascript
复制
$(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>');
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20309369

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档