Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading