Search code examples
javascriptobjectstackliteralssplice

Javascript deleting object literal item(s) inside loop


Hey all I am trying to delete a few items inside my object:

if (e = j[a].apply(j, g), e !== c && e !== j)
    $.each(j.data[0], function (key, value) {
       console.log(key, value);
       j.data.splice(1, 1);
    });

return h = e, !1

enter image description here

However, that does not seem to delete the item environment sine that is #1 and bomDescription is #0.

I also tried:

j[0].pop()

j.data[0].pop()

j.data[0].splice(1, 1)

Which non of the above work or cause an error.

What am I doing incorrectly?


Solution

  • If your object looks something like this (as it may seem from that image).

    const j = {
      data: {
        bomDescription: "hjtyj",
        environment: 2,
        ...
      }
    }
    

    Then to delete the environment property you can use delete statement like this.

    const j = {
      data: {
        bomDescription: "hjtyj",
        environment: 2
      }
    }
    
    console.log(j.data);
    delete j.data.environment;
    console.log(j.data);

    EDIT

    To delete property based on its value you can do this.

    const j = {
      data: {
        bomDescription: "hjtyj",
        environment: 2
      }
    }
    
    const removePropertyByValue = (obj, value) => {
      for (const prop in obj) {
        if (obj.hasOwnProperty(prop) && obj[prop] === value) {
          delete obj[prop];
        }
      }
    }
    
    console.log(j.data);
    removePropertyByValue(j.data, 2);
    console.log(j.data);

    EDIT II

    If the data property is an array of objects then you can do this.

    const j = {
      data: [{
        bomDescription: "hjtyj",
        environment: 2
      }]
    }
    
    const removePropertyByValue = (obj, value) => {
      for (const prop in obj) {
        if (obj.hasOwnProperty(prop) && obj[prop] === value) {
          delete obj[prop];
        }
      }
    }
    
    console.log(j.data[0]);
    removePropertyByValue(j.data[0], 2);
    console.log(j.data[0]);