Delete specific value from Array in Object

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"

>Solution :

Try using Array.prototype.splice (splice)

For example:

//print the array
console.log(my_object.contacts_id);

//delete the "contacts_id":2
my_object.contacts_id.splice(1, 1);

//print the new array
console.log(my_object.contacts_id);

Leave a Reply