So I have an object inside a json file like this:
{
"0": {
"damage_type": "Scratch",
"regions": []
},
"1": {
"damage_type": "Dent",
"regions": []
},
"2": {
"damage_type": "Dent",
"regions": [
"front side",
"front window"
]
}
}
What I am trying to accomplish is to remove the object that have empty regions. Like this:
{
"2": {
"damage_type": "Dent",
"regions": [
"front side",
"front window"
]
}
}
I am using a for loop and still unsuccessful:
jsonfile.readFile(theJsonFile, function (err, obj) {
if (err) console.error(err)
for (var i = 0; i <= Object.keys(obj).length - 1; i++) {
if (obj[i].damage_type.length < 1) {
delete obj[i]
}
}
}
Any ideas?
Calling the parsed value damages instead of obj, you can grab all entries as key/value pairs, iterate over them and remove no-region "damages" by their ids:
Object.entries(damages).forEach(([id, damage]) => {
if (!damage.regions.length) {
delete damages[id];
}
});
Alternatively, you can create a brand new structure without touching the original structure:
const entries = Object.entries(damages);
const filteredEntries = entries.filter(([_, damage]) => damage.regions.length);
const filteredDamages = Object.fromEntries(filteredEntries);
In this case first you need an array. To convert object to arrays use entry entry
let obj = {
"0": {
"damage_type": "Scratch",
"regions": []
},
"1": {
"damage_type": "Dent",
"regions": []
},
"2": {
"damage_type": "Dent",
"regions": [
"front side",
"front window"
]
}
}
converting array :
const myentry= Object.entries(obj);
Now the best way to eliminate or filter array is to use filter method and in return get the other object which have filter value.
const myFiletrObj = myentry.filter(([_, obj]) => obj.regions.length).reduce(withObjectAssign, {})
function withObjectAssign(object, [key, value]) {
return Object.assign(object, {[key]: value})
}
This will give you filtered output.
You can delete a json node by its key
var json = { ... };
var key = "foo";
delete json[key]; // Removes json.foo from the dictionary.