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.

2
  • What exactly does "dynamic" mean? Dynamic based on what? What's the input you want to turn into a delete action? Commented Aug 11, 2016 at 7: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. Commented Aug 13, 2016 at 3:41

2 Answers 2

7

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];
Sign up to request clarification or add additional context in comments.

Comments

1

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

var jsonKey = 'search.facets.source';
eval('delete jsonObj.' + jsonKey + ';');

1 Comment

Please don't use eval. Ever. Doing it properly isn't that much more complicated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.