I have a deeply nested object that I need to search to remove certain keys. The keys to remove are stored in an array indicated in the removeKeys
array.
Currently, the function only filters the top level object but scales the rest fine, it just does not filter child objects. How would I reduce the full object properly to get the desired output?
The initial unfiltered object:
let item = {
"label": "test",
"id": "test",
"styles": {
"label": "Styles",
"styles": {
"test": {
"test": "test",
"label": "test",
"test1": {
"label": "test",
"image": {
"label": "test",
"type": "test",
"value": "test",
"autoSelect": "",
"id": ""
}
}
}
}
},
"test": {
"label": "test",
"test": []
}
}
The keys to remove from the object:
const removeKeys = ["label", "type", "autoSelect"];
The recursive function to filter the nested object:
let filterObject = filterNestObject(item);
function filterNestObject(item) {
return Object.keys(item)
.filter(key => {
if (typeof item[key] === 'object') filterNestObject(item[key]);
if (!removeKeys.includes(key)) return true;
return false
})
.reduce((object, key) => {
return {
...object,
[key]: item[key]
};
}, {});
}
The expected result would be:
{
"id": "test",
"styles": {
"styles": {
"test": {
"test": "test",
"test1": {
"image": {
"value": "test",
"id": ""
}
}
}
}
},
"test": {
"test": []
}
}