I want to delete one value of an array in an object. I tried two methods, but cannot find a solution. Object function "delete" does not work and array function "splice" doesn’t work. What works?
let my_object =
{
"contacts_id":[
1,
2,
3
],
"orders_id":[
2,
3
]
}
I want to delete "contacts_id":2, so the result should look like this:
{
"contacts_id":[
1,
3
],
"orders_id":[
2,
3
]
}
I’m trying to achieve this by:
let my_object_modified = delete my_object[contacts_id][1];
This line of code does not delete the value, but sets it to "empty". The result is:
{
"contacts_id":[
1,
null,
3
],
"orders_id":[
2,
3
]
}
The second way I’m trying to delete the value is by the array function .splice:
let my_object_modified = my_object[contacts_id][1].splice(0,1);
With this code I get an error "splice is not a function"
3
Answers
use filter for this
Try using Array.prototype.splice (splice)
For example:
You can use the array method splice() to remove the desired element.
For example:
Delete a known element:
Delete any element at index 1: