如何动态删除嵌套的json键? [英] How to delete nested json key dynamically?

查看:85
本文介绍了如何动态删除嵌套的json键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是示例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
    }
  ],
  }
 }

有几种删除键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. 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中动态生成数组序列.

Above 1 & 2 are not dynamic, and 3 is one of the way but not a proper way. Because if source is present in another node then it will not work. Please anybody can tell me how to delete it dynamically in any kind of nested key. Because we can not generate sequence of array dynamically in above 2.

推荐答案

假设您是从这里开始的:

Assuming you're starting from this:

let path = 'search.facets.source';

然后逻辑很简单:找到search.facets对象,然后在其上delete obj['source'].

Then the logic is simple: find the search.facets object, then delete obj['source'] on it.

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

Step one, divide the path into the initial path and trailing property name:

let keys = path.split('.');
let prop = keys.pop();

在对象中找到facets对象:

let parent = keys.reduce((obj, key) => obj[key], jsonObj);

删除属性:

delete parent[prop];

这篇关于如何动态删除嵌套的json键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆