How to search for json using key and value and remove all mapped records?
I have Json this way
[
{
"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 "
}
]
I tried to remove entries from json based on key and value that I am passing as input, in this way
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 remote json is thus [{},{},{}]
where I want it to be like this, Removed Json [].
Ie, remove the complete entry from JSon, not just the keys and values.
I have also tried this way,
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);
}
});
}
which gives indexing problems.
I will pass the key and value, then it should remove the complete entry from json,
ex: if i pass rowKey, 2014_13 it should remove below entry from json
[{"y":"2014","m":"1313","rowKey":"2014_13","key":"m","value":"13 "}]
if records are duplicated in such a way
[{"y":"2014","m":"1313","rowKey":"2014_13","key":"m","value":"13 "}, [{"y":"2014","m":"1313","rowKey":"2014_13","key":"m","value":"13 "}]
then he must delete both entries.
Basically looking up json for key and passed value and removing all matched records. Can anyone help me with this issue?
Thank.
source to share
This sounds like a job for Array.prototype.filter () . Here's an example of using it:
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/
source to share