I have an array that looks like the following:
[
{
"id": "denuzi",
"sub":
[
{"id": "s4p58o"},
{"id": "xzbqi"},
],
},
{
"id": "4rcodm",
"sub": [],
}
]
What I am trying to do is remove an item from the array or from a nested array using a provided id.
eg if denuzi
is provided then the entire first object is removed; if s4p58o
is provided just that object from the first objects sub array is removed.
I know that I can remove an entire object with the following code:
_.remove(this.items, function(item) {
return item.id !== id;
});
But I am not sure how to make a check to remove a sub item?
You could take an iterative and recursive approach by checking the id
or call again for sub
. Exit if found.
function remove(array, id) { return array.some((o, i, a) => o.id === id ? a.splice(i, 1) : remove(o.sub || [], id) ); } var array = [{ id: "denuzi", sub: [{ id: "s4p58o" }, { id: "xzbqi" }] }, { id: "4rcodm", sub: [] }]; remove(array, 's4p58o'); console.log(array); remove(array, 'denuzi'); console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Just use Array.prototype.filter
var list = [ { "id": "denuzi", "sub": [ {"id": "s4p58o"}, {"id": "xzbqi"}, ], }, { "id": "4rcodm", "sub": [], } ] const result = list.filter(a => a.id !== 'denuzi'); console.log(result);
Without using lodash
let data = [ { "id": "denuzi", "sub": [ {"id": "s4p58o"}, {"id": "xzbqi"}, ], }, { "id": "4rcodm", "sub": [], } ] function remove(data, removeId){ return data .filter(({id}) => id!==removeId) // removes parent object if its id matches removeId .map(({id, sub}) => ({id, sub: sub.filter(({id}) => id!==removeId)})) // replaces sub array with new sub array with subobject missing } console.log(remove(data, "s4p58o")); console.log(remove(data, "denuzi"))
With lodash
const data = [ { "id": "denuzi", "sub": [ {"id": "s4p58o"}, {"id": "xzbqi"}, ], }, { "id": "4rcodm", "sub": [], } ] function remove(data, removeId){ return _.remove(data, (item) => item.id !== removeId) // removes parent object if its id matches removeId .map(({id, sub}) => ({id, sub: _.remove(sub, (item) => item.id !== removeId)})) // replaces sub array with new sub array with subobject missing } // i parse data to do a deep copy for showing the property console.log(remove(JSON.parse(JSON.stringify(data)), "s4p58o")); console.log(remove(JSON.parse(JSON.stringify(data)), "denuzi"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.