将唯一对象推送到JavaScript数组

时间:2016-04-04 13:11:27

标签: javascript arrays

如何将对象推送到仅更新该数组的指定数组?我的代码推送一个对象并更新所有数组,而不仅仅是指定的数组。

以下是数据的结构:

{
    "d": {
        "results": [
            {
                "Id": 1,
                "cost": "3",
                "item": "Project 1",
                "fiscalyear": "2014",
                "reportmonth": "July"
            }
        ]
    }
}

以下是所需结果的示例

{
    "Project 1": [
        {
            "date": "31-Jul-14",
            "rating": "3"
        },
        {
            "date": "31-Aug-14",
            "rating": "4"
        }
    ],
    "Project 2": [
        {
            "date": "31-Jul-14",
            "rating": "2"
        }
    ]
}

这是我的尝试:

var results = data.d.results;
var date;

var projectObj = {},
    projectValues = {},
    project = '';
var cost = '',
    costStatus = '';

for (var i = 0, m = results.length; i < m; ++i) {

    project = results[i]['item'];

    if (!projectObj.hasOwnProperty(project)) {
        projectObj[project] = [];
    }

    // use Moment to get and format date
    date = moment(new Date(results[i]['reportmonth'] + ' 1,' + results[i]['fiscalyear'])).endOf('month').format('DD-MMM-YYYY');

    // get cost for each unique project
    costStatus = results[i]['cost'];
    if (costStatus == null || costStatus == 'N/A') {
        cost = 'N/A';
    }
    else {
        cost = costStatus;
    }

    projectValues['rating'] = cost;
    projectValues['date'] = date;

    projectObj[project].push(projectValues);
}

这是一个不受欢迎的不良后果的小提琴: https://jsfiddle.net/yh2134jn/4/

我做错了什么?

1 个答案:

答案 0 :(得分:1)

那是因为你没有清空它的新迭代。试试这个:

for (var i = 0, m = results.length; i < m; ++i) {    
    projectValues = {};
    project = results[i]['item'];
    ....
}