Search code examples
javascriptarraysjsonreactjslodash

delete an object in a nested array which has key value


i want to delete the only low-level object(for example in below code, under personal data there are two objects... i want to delete one object where action: old) under each section, where "action": "OLD"

I'm using lodash in my project

[
  {
    "clientDetails": {
      "personalData": [
        {
          "action": "NEW",
          "id": "12345"
        },
        {
          "action": "OLD",
          "id": "12445"
        }
      ]
    },
    "clientAddress": {
      "primaryAddress": [
        {
          "action": "OLD",
          "id": "12345"
        },
        {
          "action": "NEW",
          "id": "12445"
        }
      ],
      "secondaryAddress": [
        {
          "action": "NEW",
          "id": "12345"
        },
        {
          "action": "OLD",
          "id": "12445"
        }
      ]
    }
  },
  {
    "clientDemise": {
      "deathDetails": [
        {
          "action": "NEW",
          "id": "12345"
        },
        {
          "action": "OLD",
          "id": "12445"
        }
      ]
    },
    "clientMarital": {
      "divorceInformation": [
        {
          "action": "OLD",
          "id": "12345"
        },
        {
          "action": "NEW",
          "id": "12445"
        }
      ],
      "marraigeInformation": [
        {
          "action": "NEW",
          "id": "12345"
        },
        {
          "action": "OLD",
          "id": "12445"
        }
      ]
    }
  }
]

sorry for the wrong presentation, this is the first time I'm posting a question


Solution

  • Just few lines can achieve this considering

    input = your input
    

    This peace of code will do the work

    for (var i of input) {
      for (var j in i) {
       var ob = i[j];
       for (var k in ob) {
         var index = _.findIndex(ob[k], {'action': 'OLD'});
         if (index > -1) {
           ob[k].splice(index, 1);
         }
       }
     }
    }