I need to remove items from nested arrays. I successfully have done this, however I need to keep the complete structure of the tree. The current code outputs the things object and has the element removed where name equals 'child thing 1', however my result misses a lot of other data from the original tree.
I am using lodash and deepdash as I will be working with objects with many children.
deepdash(_);
let things = {
type: 'app',
info: [],
things: [{
name: 'something',
good: false,
}, {
name: 'another thing',
good: true,
children: [{
name: 'child thing 1',
good: false,
}, {
name: 'child thing 2',
good: true,
}, {
name: 'child thing 3',
good: false,
}],
}, {
name: 'something else',
good: true,
subItem: {
name: 'sub-item',
good: false,
},
subItem2: {
name: 'sub-item-2',
good: true,
},
}],
};
let filtrate = _.filterDeep(things, (value, key, parent) => {
if (key == 'name' && parent.name !== 'child thing 1') return true;
});
console.log({ filtrate });
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script src="https://cdn.jsdelivr.net/npm/lodash/lodash.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/deepdash/browser/deepdash.min.js"></script>
Its unclear from your question what you're expected result is, as pointed out by @grodzi in the comments. However, it seems like you're just looking for a way to quickly delete sub-structures in an object while maintaining its overall integrity. Lodash provides some nifty functions that simplifies tasks like these.
Two that would help with the task at hand are get and omit
const pathsToRemove = ['things.1.children.0']; // use object dot notation (.) even for array elements
const restructure = (object, pathsToRemove) => pathsToRemove.reduce((acc, path) => {
const parentPath = path.split('.').slice(0,-1).join('.');
const [targetPath] = path.split('.').slice(-1);
let parent = _.get(acc, parentPath);
if (parent.constructor === Array) {
// this block is to prevent empty array items
parent.splice(+targetPath, 1);
return acc;
}
return _.omit(acc, path);
}, object);
console.log(JSON.stringify(
restructure(things, pathsToRemove),
null,
4
));
I think something like this would get the job done. Make sure to check this yourself though, with tests preferably if this is at all likely to be deployed.