Dynamically delete a property from a JSON object

I am currently working on a task that involves removing properties from a JSON object. I need to create a system where I can specify an array of locations from which the fields should be redacted. The JSON request I am dealing with looks like this:

{
"name": "Rohit",
"other": [{
    "tfn": "2879872934"
}, {
    "tfn": "3545345345"
}],
"other1": {
    "tfn": "3545345345"
},
"other2": {
    "other3": [{
        "tf2n": "2879872934"
    }, {
        "tfn": "3545345345"
    }, {
        "tfn": "2342342234"
    }]
},
"card": "sdlkjl",
"tfn": "2879872934",
"f": true}

To achieve this, I have identified the specific paths that need to be removed:

let paths = ['other.tfn','tfn','other1.tfn','other2.other3.tfn'];

After applying the removal process, the updated JSON object will look like this:

{
"name": "Rohit",
"other": [
    {},
    {}
],
"other1": {},
"other2": {
    "other3": [
        {
            "tf2n": "2879872934"
        },
        {},
        {}
    ]
},
"card": "sdlkjl",
"f": true}

I feel there might be a more efficient way to implement the code below:

paths.forEach(function (path) {
           let keys = path.split('.');
           deepObjectRemove(jsonObject, keys);
        });

This is the method used for removal:

var deepObjectRemove = function(obj, path_to_key){
if(path_to_key.length === 1){
    delete obj[path_to_key[0]];
    return true;
}else{
    if(obj[path_to_key[0]] && Array.isArray(obj[path_to_key[0]])) {
        obj[path_to_key[0]].forEach(function (value) {
            deepObjectRemove(value, path_to_key.slice(1));
        });
        //return deepObjectRemove(obj[path_to_key[0]], path_to_key.slice(1));
    }else if(obj[path_to_key[0]]){
        deepObjectRemove(obj[path_to_key[0]], path_to_key.slice(1));
    }else{
        return false;
    }
}};

Answer №1

function removeNestedProperty(obj, prop) {
const parts = prop.split(".");
let current;
while (current = parts.shift()) {
if (!obj) {
return;
}
const item = obj[current];
if (item !== undefined) {
if (!parts.length) {
delete obj[current];
}
if (item instanceof Array) {
return item.forEach((val) => removeNestedProperty(val, parts.join(".")));
}
}
obj = item;
}
}

const obj = {
a: {
b: {
c: "1",
d: 0
}
},
b: [
{
a: {
b: "0",
c: "1"
}
},
{
a: {
b: "0",
c: "1"
}
}
]
};
console.log("before", obj);
[
"a.b.c",
"b.a.c"
].forEach((prop) => deepObjectRemove(obj, prop));
console.log("after", obj);

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

Display content based on specific categories from a JSON file using AngularJS

I am looking to display a list of products categorized that are coming in a json using Angular. The json data I have is: { "MAIN MENU ": [{ "id_prod": "1", "name_prod": "Artisanal chicken nuggets with mustard sauce", "descrip_ ...

Node.js's module-only scope concept allows variables and functions defined within

Currently, I am attempting to create a function that can set a variable at the top-level scope of a module without it leaking into the global scope. Initially, I believed that implicit variable declarations within a module would remain confined to the modu ...

Storing JSON information on your iPhone: Should you store the JSON string as is, or convert it into an object and utilize NSCoding + NSKeyedArchiver for storage?

When it comes to creating an iPhone application, one important aspect to consider is how to handle data retrieved from a remote server. In my specific case, I am using the Json Framework to parse json data and display it in a UIview. The question arises wh ...

Is it possible to send an email with an attachment that was generated as a blob within the browser?

Is there a way to attach a file created in the browser as a blob to an email, similar to embedding its direct path in the url for a local file? The file is generated as part of some javascript code that I am running. Thank you in advance! ...

How can I ensure that I am only retrieving the first object within a "for loop" in vuejs and returning its value without getting the rest?

Why am I only able to retrieve the value of the first object in my "for loop" and not all three values as intended? var app = new Vue({ el: '#app', data: { myObj: [ {name: 'Hello', age: 10}, {name: ...

Anticipating the execution of pool.query within a callback function in the Express framework

Within an Express post endpoint, I am utilizing crypto.generateKeyPair. After generating the key pair, I wish to store it in my database and then return the ID of the inserted row within the same endpoint. Here is the code snippet for the endpoint: app.p ...

Connecting NGINX to a Node.js cluster with proxy_pass

After setting up both a NGINX server and a node.js process, the node.js code structure is as follows: function initiateCluster() { var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i ...

The replace function fails to recognize Cyrillic characters when combined with the /b flag

Struggling with a persistent issue, I've noticed that my code works perfectly with Latin characters but fails to recognize Cyrillic characters when using jQuery. $('p').each(function() { var $this = $(this); $this.html($this.text().re ...

Update the color of navigation items to reflect their active status

Here is the snippet of HTML code: <header> <nav> <a href="#" id="menu-icon"></a> <ul> <li><a href="#"">Home</a></li> <li><a href="#">About</a></li> & ...

Content that is dynamically generated by a database

I have been working on creating a unique wall feature for my website, inspired by Facebook. My aim is to allow users to submit form data and have it validated before storing it in a database. Additionally, I want this stored data to be displayed in a desig ...

Prisma encountered an error with the database string: Invalid MongoDB connection string

I'm encountering an issue with my MongoDB data provider, as I am informed that my connection string is invalid. The specific error message states: The provided database string is invalid. MongoDB connection string error: Missing delimiting slash betw ...

Transferring PHP array to JavaScript with the help of AJAX

I've been working on integrating Google Maps and Instagram in a project of mine. My main challenge is figuring out how to pass the coordinates of Instagram photos from my PHP file to my JavaScript file using AJAX. I'm quite lost when it comes to ...

Error: The middleware function is not recognized | Guide to Transitioning to React Redux Firebase v3

After utilizing these packages for my project, I encountered an error in middleware composition while creating a new react app with create-react-app. Below are the packages I have included. Can someone please help me identify what is missing here? HELP I ...

Load HTML table values dynamically with Ajax post page load in PHP

My goal is to retrieve the connectivity status of available servers in a database on a PHP page. <tbody> <?php foreach ($data['servers'] as $server) { ?> <tr> <td class=""><?php echo $server->server_ ...

What strategies can I use to dynamically update the .active class in jquery so it doesn't only target the initial one?

Utilizing bootstrap for tab-fade functionality has been successful so far. However, I am facing an issue when trying to select multiple active classes instead of just one. My current JQuery code only changes the text in the first element with the "active" ...

Using HTML, CSS, and jQuery to create a master-detail feature

I'm looking to implement a master-detail layout, so I decided to follow this tutorial for guidance: While trying to replicate the tutorial, I encountered an issue with my code. Here's the code snippet that I am working on: HTML/jQuery <!DO ...

Exploring the Live Search Functionality on an HTML Webpage

I am attempting to create a live search on dive elements within an HTML document. var val; $(document).ready(function() { $('#search').keyup(function() { var value = document.getElementById('search').value; val = $.trim(val ...

The concept of inheriting directives/scopes

Just wondering if directives declared within a Component in Angular 2 automatically apply to its children Components. And when it comes to variables declared on the Component, do they get inherited by the children Components or must they be explicitly pa ...

Tips for refreshing the direction route in google-maps-react

I have an array of coordinates, and when I add a new coordinate to the array, I want the route direction on the map to update accordingly. This is the code snippet from my googlemap.js file: /* global google */ import React, { Component } from "react ...

The POST request to write to a JSON file using fs.fileWrite is malfunctioning and unable to establish a connection with localhost

I am currently facing challenges with expressing myself effectively. My struggle lies in getting a post request to function properly. I aim to use the post request to update an item in a cart.json file, leveraging Node.js's fs.fileRead and fs.fileWrit ...