0

This is the sample 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
    }
  ],
  }
 }

There are several ways to delete 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; });

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.

Suvam Roy
  • 1,282
  • 2
  • 11
  • 21
  • What exactly does "dynamic" mean? Dynamic based on what? What's the input you want to turn into a delete action? – deceze Aug 11 '16 at 07:44
  • Dynamic means, I want a function which will return the json after removing the key whatever I pass the key and jsonObj to the function, can you please provide a complete function. – Suvam Roy Aug 13 '16 at 03:41

2 Answers2

6

Assuming you're starting from this:

let path = 'search.facets.source';

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

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

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

Find the facets object in your object:

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

Delete the property:

delete parent[prop];
deceze
  • 510,633
  • 85
  • 743
  • 889
1

I have found out another solution, it is very easy.

var jsonKey = 'search.facets.source';
eval('delete jsonObj.' + jsonKey + ';');
Suvam Roy
  • 1,282
  • 2
  • 11
  • 21