如何使用键和值搜索json并删除所有匹配的条目?

时间:2015-06-08 18:25:32

标签: javascript jquery arrays json

我这样对待Json,

[
{
    "y": "2014",
    "m": "1313",
    "rowKey": "2014_13",
    "key": "m",
    "value": "13   "
},
{
    "y": "2014",
    "m": "1313",
    "rowKey": "2014_13_1",
    "key": "m",
    "value": "13   "
},
{
    "y": "2014",
    "m": "1313",
    "rowKey": "2014_13_2",
    "key": "m",
    "value": "13   "
}

我尝试根据我传递的键和值来删除json中的条目,这样,

function findAndRemove(array, property, value) {

    for(var i=0;i<array.length;i++){
        delete array[i].y;
        delete array[i].m;
        delete array[i].rowKey;
        delete array[i].key;
        delete array[i].value;
    }
}

My Removed json是这样的,[{},{},{}]

我希望它是这样的,删除了Json []。

即,从JSon中删除完整的条目,而不仅仅是键和值。

我也试过这种方式,

    function findAndRemove(array, property, value) {
    $.each(array, function(index, result) {
        if(undefined != result[property] && result[property] == value && array.hasOwnProperty(property)) {
            //Remove from array
            array.splice(index, 1);
        }    
    });
}

这给出了索引问题。

我将传递键和值,然后它应该从json中删除完整的条目,

例如:如果我传递rowKey,2014_13它应该从json

中删除以下条目
 [{"y":"2014","m":"1313","rowKey":"2014_13","key":"m","value":"13   "}]

如果条目以这种方式重复,

 [{"y":"2014","m":"1313","rowKey":"2014_13","key":"m","value":"13   "}, [{"y":"2014","m":"1313","rowKey":"2014_13","key":"m","value":"13   "}]

然后它应该删除这两个条目。

基本上搜索json以获取密钥和值,并删除所有匹配的条目。 任何人都可以帮我解决这个问题吗?

感谢。

1 个答案:

答案 0 :(得分:5)

这听起来像是Array.prototype.filter()的工作。以下是使用它的示例:

var data = [{
    "y": "2014",
    "m": "1313",
    "rowKey": "2014_13",
    "key": "m",
    "value": "13   "
}, {
    "y": "2014",
    "m": "1313",
    "rowKey": "2014_13_1",
    "key": "m",
    "value": "13   "
}, {
    "y": "2014",
    "m": "1313",
    "rowKey": "2014_13_2",
    "key": "m",
    "value": "13   "
}];

var good = data.filter(function(record) {
    return record['rowKey'] !== '2014_13';
});

console.log(good);

JSFiddle:http://jsfiddle.net/4vbxLpwo/