javascript - 如何删除嵌套数组中存在名称属性未定义的 JSON 对象

标签 javascript jquery json

从下面的 JSON 中,我得到了 areaQuotas 数组,其中一些数组的 name 属性不存在。

[
  {
    "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"
  },

]

从下面的 JSON 中,我得到了 areaQuotas 数组,其中一些 name 属性不存在。

如何删除areaQuotas数组中所有未定义name属性的对象

我已经尝试过,如下所示

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

这是我的 fiddle

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

最佳答案

您可以将 forEachfilter 一起使用。

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

这是更新后的 fiddle :https://jsfiddle.net/o2gxgz9r/65246/

关于javascript - 如何删除嵌套数组中存在名称属性未定义的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51920880/

相关文章:

jquery - 图像弹出不显示

java - 我应该如何在 Tomcat servlet 中解析 POST 请求消息的内容

javascript - 以编程方式填充组合框 dojo (1.8) 的最佳方法是什么?

javascript - 用于查找页面上使用的所有字体的脚本

javascript - 如何根据内容调整容器的大小而不重复相同的代码行?

javascript - 在媒体窗口中选择图片后添加/更新自定义字段 (Wordpress)

javascript - Angular (jquery timepicker)无法获取输入值

javascript - 可排序列表不会排序(jQuery/Javascript)

c# - 将 JSON 数据动态嵌套到数据表 C#

javascript - 为什么这里的仪表板状态没有被 $state.go ('dashboard' ... 命中?