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
:
delete search.facets.source
delete jsobObj['search']['facets']['source']
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.
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
:
delete search.facets.source
delete jsobObj['search']['facets']['source']
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.
Share Improve this question asked Aug 11, 2016 at 7:43 Suvam RoySuvam Roy 1,2802 gold badges11 silver badges21 bronze badges 2- What exactly does "dynamic" mean? Dynamic based on what? What's the input you want to turn into a delete action? – deceze ♦ 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 plete function. – Suvam Roy Commented Aug 13, 2016 at 3:41
2 Answers
Reset to default 7Assuming 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];
I have found out another solution, it is very easy.
var jsonKey = 'search.facets.source';
eval('delete jsonObj.' + jsonKey + ';');