skip to Main Content

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


  1. use filter for this

    let my_object =  
    
    {
       "contacts_id":[
          1,
          2,
          3
       ],
       "orders_id":[
          2,
          3
       ]
    }
    
    my_object.contacts_id = my_object.contacts_id.filter(x => x!==2)
    
    console.log(my_object)
    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
  3. You can use the array method splice() to remove the desired element.

    For example:

    Delete a known element:

    let my_object = {
       "contacts_id":[
          1,
          2,
          3
       ],
       "orders_id":[
          2,
          3
       ]
    };
    
    let index = my_object["contacts_id"].indexOf(2);
    
    if (index > -1) {
      my_object["contacts_id"].splice(index, 1);
    }
    
    console.log(my_object);
    

    Delete any element at index 1:

    let my_object = {
       "contacts_id":[
          1,
          2,
          3
       ],
       "orders_id":[
          2,
          3
       ]
    };
    
    my_object["contacts_id"].splice(1, 1);
    
    console.log(my_object);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search