Last active
November 9, 2017 18:18
-
-
Save iuliaL/23236b8e452e2895adbeb639cf62027b to your computer and use it in GitHub Desktop.
Delete a (nested) key from JSON object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// works with just one key to delete (for now) by proving | |
// complete path (i.e 'rows.0.panels.0.password') or | |
// just key name (i.e 'password') | |
import '_' from 'lodash'; | |
const DOT_SEPARATOR = "."; | |
function checkPath(arr, object){ | |
arr.forEach((chunk, index, array)=> { | |
if(_.isObject(object[chunk]) ){ | |
if(index != array.length - 1){ | |
checkPath(arr.slice(index + 1), object[chunk]); | |
} else { | |
//is obj but IS last then DELETE | |
delete object[chunk]; | |
} | |
} else { | |
delete object[chunk]; | |
} | |
}); | |
} | |
const recursiveClean = (object, keysToDelete) =>{ | |
Object.keys(object).forEach(key =>{ | |
if (keysToDelete.indexOf(DOT_SEPARATOR) > -1 ){ | |
const chunks = keysToDelete.split(DOT_SEPARATOR); | |
if((chunks[0] == key) && _.isObject(object[key])){ | |
checkPath(chunks, object); | |
} | |
} else if (keysToDelete.indexOf(key) > -1){ | |
delete object[key]; | |
} else if (_.isObject(object[key])) { | |
return recursiveClean(object[key], keysToDelete); | |
} | |
}); | |
return object; | |
}; | |
const deleteKeyFromObject = (obj, keysToDelete) => { | |
return recursiveClean(_.clone(obj, true), keysToDelete); | |
}; | |
// json object to test with | |
const jsonObj = { | |
"__inputs": [], | |
"__requires": [ | |
{ | |
"type": "grafana", | |
"id": "grafana", | |
"name": "Grafana", | |
"version": "4.1.0" | |
}, | |
{ | |
"type": "panel", | |
"id": "powelectrics-train-table-panel", | |
"name": "Powelectrics Train Table", | |
"version": "0.0.1" | |
} | |
], | |
"annotations": { | |
"list": [] | |
}, | |
"rows": [ | |
{ | |
"collapse": false, | |
"height": "250px", | |
"panels": [ | |
{ | |
"apiBaseUrl": "http://api.XXXXXXX.com", | |
"fontSize": "100%", | |
"id": 1, | |
"pageSize": null, | |
"password": "XXXXXX", | |
"scroll": true, | |
"showHeader": true, | |
"sort": { | |
"col": 0, | |
"desc": true | |
}, | |
"span": 12, | |
"targets": [ | |
{} | |
], | |
"tenantName": "XXXXXXXX", | |
"type": "table", | |
"username": "XXXXXXXXXX" | |
} | |
], | |
} | |
], | |
}; | |
console.log(deleteKeyFromObject(jsonObj, 'password')); | |
console.log(deleteKeyFromObject(jsonObj, 'rows.0.panels.0.password')); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment