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

Showing the outcome of the AJAX call

I have searched extensively for information on how to use AJAX, but I have been unable to find a resource that clearly explains the concept and its workings. When I send an AJAX request to a PHP file using the code below, I can see the response in Mozilla ...

Refreshing the view following a model update within an AJAX call in the Backbone framework

I'm struggling with my code as I can't seem to get my view to update after a model change. var ResultLoanView = Backbone.View.extend({ id:"result", initialize: function(){ this.render(); this.on('submissionMa ...

What is the solution using high-order functions?

I am struggling with a problem I came across on the internet. The task at hand is to identify all unique elements in an array that are less than 10, calculate the sum of these elements, and then multiply each element in the array by this sum. I have heard ...

what sets apart parseint from minus

Typically, my approach for parsing numbers in JavaScript involves the following code snippet: var x = "99" var xNumber = x - 0 as opposed to using: var xNumber = parseInt(x) I am curious to know if there are any potential issues with this method in ter ...

What causes array_diff to behave in a unique manner when comparing arrays obtained from an input form?

I have created an input form with three text areas: <form method="POST" action="unique_value_processor.php"> <textarea cols="50" rows="8" name="usedurls"></textarea> <textarea cols="50" rows="8" name="freshurls"></textarea> & ...

Converting large objects over 2MiB into JSON in Asp.net

Currently, we are conducting Performance tests to determine the speed of Kendo UI for our specific needs. Our testing involves working with a large database that consists of approximately 150 columns and 100,000 rows. We need to retrieve table rows using ...

The value of `this` from React Store is currently returning null

I'm facing an issue where the this keyword is coming back as null in my store within a React component. I suspect that binding might be necessary, but I'm not entirely sure. Additionally, I am utilizing React Router and have the component wrapped ...

Is it possible to transmit an array using $.ajax and specify the dataType as json?

I am currently attempting to send a JavaScript array to my .php file handler and store it in my database. Although the request is successful, it seems like my array isn't being posted/saved correctly. When I check the POST request source, it shows up ...

Creating a Timeless Banner with the Magic of `background:url()`

I have a banner placed within a div tag that displays my banner image. I am trying to create a fading effect when transitioning to the next image, but I am struggling to achieve this. I attempted to use jQuery fadeIn(), however, it did not work as expected ...

Turning off JSON rearrangement

Currently, I am in the process of generating JSON data that needs to be validated through an ajax call. Below is the JSON data that I have created: {"telephone1":"66", "telephone2":"66", "fax":"66", "mobilePhone":"66", "dateEffectiveChangementAdresse ...

Looking for elements that match in an array

Currently working on a basic program that requires checking if the input string exists in the array. To simplify it, for example, if someone types 'Ai', I want the program to display all elements in the array containing the letters 'Ai&apos ...

Remove an item from the DOM instantly with React

Having trouble synchronously removing a child from the container? Here is a simplified code snippet demonstrating the current solution using the useState hook. type ChildProps = { index: number; id: string; remove: (index: number) => void; }; fun ...

Tips for adjusting the progress bar to 100% and back to 0%

My goal is to increase the progress bar percentage with each click. Currently, it only goes up to 75%. When saving, it should show 100%, but it's not displaying that properly. On clicking the back button, it should reset to 0% on the third click. HTM ...

The console object in Chrome_browser is a powerful tool for debugging and

Having difficulty saving an amchart graph to the localstorage and retrieving the data successfully. https://i.stack.imgur.com/lJ3bJ.png In the original object, there is a mystery b, while in the new object, it appears as a normal object. In Internet Expl ...

What are the advantages of using React JS for a Single Page Application compared to server-side rendering?

Currently, I am faced with a conundrum when it comes to selecting the best approach for a highly scalable project. On one hand, server-side rendering using Node.js with Express (utilizing EJS) to render full HTML pages is an option. On the other hand, ther ...

Navigating through directory paths in JavaScript can be a daunting task for many

In my app.js file, I've included the following code: app.use(multer({dest:'./uploads'})) What does './uploads' refer to here? It is located in the same directory as app.js. In what way does it differ from simply using uploads? I ...

Requiring addresses for Google Maps in order to display directions

To display the directions between two addresses based on the chosen transportation mode, I need to pass the addresses to the code in page 2. After the user selects two cities from a Dropdown box on page 1, they will be sent to the code to show their locati ...

What is the best way to utilize d3.domain for extracting both d3.min and d3.max values from various columns within a JSON dataset?

I have a JSON file that contains data from different years for "male," "female," and "both" categories. I want to set the minimum value in my domain to be the lowest value across all three columns and do the same for the maximum value. Is there a way for ...

What could be the reason that Vue is not evaluating anything when the directive @click is specified as "true && method"?

Consider the following scenario: LandingPage.vue <template> <button @click="handleClick">Click Me</button> </template> <script> export default { methods: { handleClick() { this.$emit("click"); } } }; < ...

Comparing boolean values in React JS

I am working with a React JavaScript code in which I am iterating through a series of boolean values. The issue I am facing is that when 'data.nextrow' is false, I expect nextrow1 to also be false but it ends up being set to true instead. co ...