在javascript中从Json数据中删除

时间:2013-11-21 08:05:11

标签: javascript jquery json

"[
"{\"StudentID\":5042,\"Status\":\"Joshua picked up  from school [0]    at 12:41PM and reached home [0] at    12:43PM\",\"Date\":\"2013-11-20\"}",    

"{\"StudentID\":5042,\"Status\":\"Joshua picked up  from school [0]    at 12:41PM and reached home [0] at    12:43PM\",\"Date\":\"2013-11-20\"}",    

"{\"StudentID\":5042,\"Status\":\"Joshua picked up  from school [0]    at 12:41PM and reached home [0] at    12:43PM\",\"Date\":\"2013-11-20\"}"]

我在java脚本中有这种类型的数据我想删除那些不在当前周日期的记录。

2 个答案:

答案 0 :(得分:1)

1)使用 $.each() 迭代解析的JSON 2)要获得周数,请使用以下protype method

Date.prototype.getWeek = function () {
    var onejan = new Date(this.getFullYear(), 0, 1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}

使用:

var todayWeekNo = new Date().getWeek();

3)检查它们是否属于同一周使用

var isEqual = (todayWeekNo == new Date(j.Date).getWeek());

4)如果不相等,请使用索引将其删除。

最后,

Date.prototype.getWeek = function () {
    var onejan = new Date(this.getFullYear(), 0, 1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}

var arr = [{
    "StudentID": 5041,
        "Status": "Joshua picked up  from school [0]    at 12:41PM and reached home [0] at    12:43PM",
        "Date": "2013-11-20"
}, {
    "StudentID": 5042,
        "Status": "Joshua picked up  from school [0]    at 12:41PM and reached home [0] at    12:43PM",
        "Date": "2013-11-20"
}, {
    "StudentID": 5043,
        "Status": "Joshua picked up  from school [0]    at 12:41PM and reached home [0] at    12:43PM",
        "Date": "2013-11-20"
}];


var todayWeekNo = new Date().getWeek();
$.each(arr, function (i, j) {
    var isEqual = todayWeekNo == new Date(j.Date).getWeek();
    if (!isEqual) {
        delete arr[i];
    }
});

JSFiddle

<强>更新

  

Since Delete won't remove the element from the array it will only set the element as undefined.

所以我尝试使用 arr.splice(i, 1); ,但它无效。参考此question,这是另一种方法。

var todayWeekNo = new Date().getWeek();
for (var i = 0; i < arr.length;) {
    var isEqual = (todayWeekNo == new Date(arr[i].Date).getWeek());
    if (!isEqual) {
        arr.splice(i, 1);
    } else {
        i++;
    }
}

希望你明白。

答案 1 :(得分:0)

根据需要调用此代码以减少。

function reduceJSON(data) {
    $.each(data, function(key, value) {
        var returnObject = {};
        if(/* Your Condition Here */) {
            returnObject.push(value);
        }
    });
    return returnObject;
}

yourJSON = reduceJSON(yourJSON);