Pawan
Pawan

Reputation: 32321

How to remove JSON Objects whose name attribute is undefined present in a nested array

From the below JSON i have got areaQuotas array , for some of them the name attribute is not present .

[
  {
    "forums": "",
    "resource": {
      "dhjName": "myvhp",
      "dhj": {
        "areaProgramValue": "123",
        "areaQuotas": [
          {
            "areaQuotaValue": "1234",
            "name": "acc"
          },
          {
            "areaQuotaValue": "12345",
            "name": "pro"
          }
        ],
        "methodType": "DGH",

      }
    },
    "task": "create"
  },
  {
    "forums": "",
    "resource": {
      "dhjName": "myvhp",
      "dhj": {
        "areaProgramValue": "123",
        "areaQuotas": [
          {
            "areaQuotaValue": "1234",
            "name": "acc"
          },
          {
            "areaQuotaValue": "12345",
            "name": "pro"
          },
          {
            "areaQuotaValue": "5666"
          },
          {
            "areaQuotaValue": "7666"
          }
        ],
        "methodType": "DGH",

      }
    },
    "task": "create"
  },

]

From the below JSON i have got areaQuotas array , for some of them the name attribute is not present .

How to remove all the Objects whose name attribute is undefined for the areaQuotas array

I have tried as shown below

test = test.filter((obj) =>  typeof obj.resource.dhj.areaQuotas.name === 'undefined');

This is my fiddle

https://jsfiddle.net/o2gxgz9r/65225/

Upvotes: 0

Views: 46

Answers (1)

gagan
gagan

Reputation: 269

You can use forEach along with filter.

test.forEach(item => {
  item.resource.dhj.areaQuotas = item.resource.dhj.areaQuotas.filter(
    areaQuota => {
      return areaQuota.hasOwnProperty('name');
    }
  );
});

Here is the updated fiddle: https://jsfiddle.net/o2gxgz9r/65246/

Upvotes: 3

Related Questions