I have tried many different ways to parse and delete keys with empty values dynamically from a JSON file, using only JavaScript.
As of now, I have been able to delete keys that are not nested, with the exception of empty strings with a length greater than 0.
My main ask is how to access subvalues, evaluating the nested keys and deleting only the nested key - right now I end up deleting the root key.
Pardon if this is a duplicated question, but I could not find any implementation for this particular case that worked for me here or elsewhere.
Here is what I have so far:
//DATA
let input = '{"first_name": "","last_name": "Smith","email":"[email protected]","gender": null,"invitations": [{"from": "test","code": ""}],"company": {"name": "dds","industries": [""]},"address": {"city": "New York","state": "NY","zip": "10011","street": " "},"new Value": ""}';
//MAIN FUNCTION
function removeEmptyFields(inputJSON) {
let data = JSON.parse(inputJSON);
//accessing top level keys (case1)
for (let key in data) {
let item = data[key];
//dig deeper if value not at top level
if (item !== null && typeof item !== 'object') {
deleteRecord(item)
} else {
lookDeeper(item)
}
if (item === null && typeof item === 'object') {
deleteRecord(item)
}
//function that deletes empty records
function deleteRecord(item) {
// console.log(item + "#");//function that deletes empty records
if (item === null || item === undefined ||
item.length === 0) {
delete data[key];
}
}
//function to access values nested one level (case2)
function lookDeeper(key) {
if (typeof key === 'object' && typeof key != null) {
for (let key2 in key) {
if (typeof key[key2] === 'object' && typeof key[key2] != null) {
console.log()
for (let subItem in key[key2]) {
// deleteRecord(key2[subItem])
}
}
deleteRecord(item[key2])
lookDeeper(item[key2]);
}
}
}
}
return data;
}
let output = removeEmptyFields(input)
console.log(output);
//CASES:
//1-> flat object:
//data[key]
//2 -> array/object
//data[key][array-index]
//3 ->object/object
//data[key][subkey]
//4 ->object/object/array
//data[key][subkey][array-index]
// Test cases in order, and delete nulls at the very end. return data as result
item === null && typeof item === 'object'thats never true.lookDeeperexpects a key, you pass a valuelookDeeper(item[key2]);typeof nullis "object" ...