What is the best way to remove a nested JSON key in a dynamic manner

Here is a sample json for reference:

{
"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 multiple ways to remove the 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;
     });

Options 1 and 2 are static, while option 3 is a potential solution but may not work effectively if the 'source' key is nested elsewhere in the JSON. Can anyone suggest a dynamic method to delete the key in any nested structure, as it is not feasible to predict the array sequence dynamically as in options 1 and 2?

Answer №1

Let's assume you are starting with the following:

let path = 'search.facets.source';

The process is straightforward: first, locate the search.facets object, then perform delete obj['source'] on it.

Firstly, separate the path into the initial path and the final property name:

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

Locate the facets object in your object:

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

Now, remove the property:

delete parent[prop];

Answer №2

I stumbled upon a different resolution, and it's incredibly straightforward.

let jsonIdentifier = 'search.filters.category';
eval('remove jsonContent.' + jsonIdentifier + ';');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Showing content based on the route - Angular

I'm struggling to hide the navbar based on a specific route in my application. I have managed to subscribe to the route changes, but I am having difficulty changing the display property accordingly. Here is what I have so far: export class AppCompo ...

Babel fails to substitute arrow functions

After setting up babel cli and configuring a .babelrc file with presets to es2015, I also installed the es2015 preset. However, when running the command babel script.js --out-file script-compiled.js, I noticed that arrow function syntax (=>) was still p ...

While going through multiple JSON links, I encountered a JSON decode error

I'm facing an issue with a JSON data structure that contains information on various "videos". Each "video" in the JSON includes a link to another JSON file containing "messages". My goal is to loop through the links to the "message" JSON files and in ...

The full height of the image cannot be captured by html2canvas

It baffles me that html2canvas is failing to capture the full height of the div. html2canvas($container, { height: $container.height(), onrendered: function(canvas) { var data = canvas.toDataURL('image/png'); ...

Is it possible for a PHP form to generate new values based on user input after being submitted?

After a user fills out and submits a form, their inputs are sent over using POST to a specified .php page. The question arises: can buttons or radio checks on the same page perform different operations on those inputs depending on which one is clicked? It ...

What is the correct way to generate an await expression by utilizing recast/esprima?

I have an issue with a JavaScript function export const cleanUp = async () => { await User.destroy({ where: {} }); }; I am attempting to add a line below await User.destroy({ where: {} }) using recast.parse(`await ${module}.destroy({ where: {} } ...

Stable and persistent popup window that remains at the forefront in a Chrome extension

Currently developing a Google Chrome extension and seeking assistance in creating a popup window that remains fixed in one corner while staying on top of all other windows. Here is a reference image for clarification: https://i.stack.imgur.com/IPw7N.jpg ...

Problem with roles assigned through reactions on Discord

I've been working on a discord bot reaction roles command and everything seems to be going smoothly, except for one issue that I'm facing. After booting up the bot and running the command to create the embed, everything works fine. However, when ...

tips for repurposing a jquery function

Similar Question: JQuery: Issue with $(window).resize() not triggering on page load In my jQuery code snippet below, I am trying to make a function work both on window resize and page load without duplicating the code. The current implementation works ...

Develop a personalized event using JavaScript and activate it

I have encountered a problem with a Google ad that expands on click and closes when the close button is hit. However, due to changing conditions, I now need it to expand first and then automatically close after a certain time. Additionally, every time it e ...

Blur the AngularJS button after it is clicked

Currently, I am utilizing AngularJS within a Salesforce setup. One of the functionalities involves a button that triggers several automations in Salesforce upon being clicked, which works perfectly fine. However, the automation process takes approximately ...

External function does not support jQuery types

In my theme.js file, I currently have the following code: jQuery(function ($) { accordion($) }) const accordion = ($) => ... By placing the accordion function directly into the jQuery function, Typescript is able to assist with the installed jquery ...

"Encountering issues with running Mongoimport on Mac due to a variable within the

I am encountering an issue while attempting to import a JSON file into MongoDB. Interestingly, when I use this specific command, the file imports successfully: mongoimport -d reps_development -c users --jsonArray --file ~/reps/scripts/mockUserData.json H ...

Can PHP's CURL handle cookies?

Recently, I set up a poll using PHP that allows voting without the need for an account. However, I became concerned about the possibility of the poll being vulnerable to hacking and spam votes. I discovered that I could potentially vote multiple times by ...

Is it possible to incorporate a selection box along with the Raycaster in Three.js?

In my GLTF scene, I have been exploring the use of the example selection box (code) to select multiple meshes. Unfortunately, the current approach is providing inaccurate results as it selects based on the centroid of each mesh and includes meshes that ar ...

Encountered an issue while attempting to start an SSR server with inertiajs

I followed all the necessary steps to set up an ssr application, but unfortunately, I am encountering some difficulties. config/inertia export const inertia: InertiaConfig = { view: 'app', ssr: { enabled: true, autoreload: process.en ...

Display the initial x list items without utilizing ngFor in Angular 2

In the template, there are 9 <li> elements, each with a *ngIf condition present. It is possible that 5 or more of them may return true, but the requirement is to only display the first 4 or less if needed. Priority is given to the order of the < ...

Transferring information from Vue Component to Vuex storage

I am currently working with a Laravel API route that looks like this: Route::get('c/maintenances/{contractor_user_id}', 'Maintenance\Api\ApiContractorMaintenanceController@index'); The contractor_user_id parameter is dynamic ...

When a new entry is added to the database, automatically refresh a <div> section within an HTML document

I have a basic webpage that showcases various products stored in the database. My goal is to implement an updater feature where, if a user adds a new product, the page will automatically display the latest addition in a specific div. I attempted to refere ...