Problem Statement:
Delete an element from a nested array in Javascript
Let's discuss.
Deleting an element from a regular array is easy.
Option 1 (when you have a predicate) :
const newArray = oldArray.filter((element) => /*predicate*/)
Option 2 (when you have an index)
Either use filter with an additional index
argument or make use of splice
oldArray.splice(indexToBeDeleted,1)
Now, how would you delete an element from a nested array in an object? Say this is your object structure
const blog = {
title : "Hello World",
post = [
{
title: "Article 1",
references: [
{
url: "www.example.com",
author: "John Smith"
},
{
url: "www.example2.com",
author: "Kent Dodds"
},
{
url: "www.example3.com",
author: "Kyle Smith"
}
]
}
]
}
This is a typical example we all see everyday. Say the second reference for the first post is no more valid and it has to be deleted for it to be saved to DB.
Usually, the location of a nested element in an object is specified by its path
. Here, for our second reference , the path
is articles[0].references[1]
.
How to delete this ?
The native delete
option in JS is not valid for arrays as it leaves behind an ugly undefined
in the array, that is if you can traverse to that nested array. Also, when given a path you will have to write your own logic to traverse through the object.
Another good alternative is to use lodash
. It comes with set
& get
methods which are just perfect for this usecase when used in conjunction.
We want to delete the element at articles[0].references[1]
path from blog
object .
Trick is to devide the above path into two parts
- parentArrayPath :
articles[0].references
- childIndex : 1
const _ = require('lodash') (OR) import * as _ from 'lodash' // depending on where you are using this library
const refs = _.get(blog, parentArrayPath)
refs.splice(childIndex,1)
_.set(blog, parentArrayPath, refs)
Now, blog
object will look like
const blog = {
title : "Hello World",
post = [
{
title: "Article 1",
references: [
{
url: "www.example.com",
author: "John Smith"
},
{
url: "www.example3.com",
author: "Kyle Smith"
}
]
}
]
}
Do let me know if you have a better alternative. Happy to discuss.
Top comments (0)