如何动态删除嵌套的json键?

Suv*_*Roy 0 javascript json angularjs

这是示例 json:

{
"search": {
"facets": {
  "author": [

  ],
  "language": [
    {
      "value": "nep",
      "count": 3
    },
    {
      "value": "urd",
      "count": 1
    }
  ],
  "source": [
    {
      "value": "West Bengal State Council of Vocational Education & Training",
      "count": 175
    }
  ],
  "type": [
    {
      "value": "text",
      "count": 175
    }
  ],
  }
 }
Run Code Online (Sandbox Code Playgroud)

有几种方法可以删除 key search.facets.source:

  1. delete search.facets.source
  2. delete jsobObj['search']['facets']['source']
  3. var jsonKey = 'source'; JSON.parse(angular.toJson(jsonObj), function (key, value) { if (key != jsonKey) return value; });

以上 1 & 2 不是动态的,而 3 是一种方式但不是一种正确的方式。因为如果源存在于另一个节点中,那么它将不起作用。请任何人都可以告诉我如何在任何类型的嵌套键中动态删除它。因为我们不能在上面的2中动态生成数组序列。

dec*_*eze 5

假设你从这个开始:

let path = 'search.facets.source';
Run Code Online (Sandbox Code Playgroud)

那么逻辑很简单:找到search.facets对象,然后delete obj['source']就可以了。

第一步,划分path为初始路径和尾随属性名:

let keys = path.split('.');
let prop = keys.pop();
Run Code Online (Sandbox Code Playgroud)

在facets对象中查找对象:

let parent = keys.reduce((obj, key) => obj[key], jsonObj);
Run Code Online (Sandbox Code Playgroud)

删除属性:

delete parent[prop];
Run Code Online (Sandbox Code Playgroud)