What is the best way to eliminate particular elements from a nested JSON payload in JavaScript?

I am in need of creating a function that can scan through a nested JSON structure to locate specific elements and delete all occurrences of those elements, even if they are within an array.

Consider this JSON example:

{
    "userId": "John991",
    "group1": {
        "color": "red",
        "height": "100",
        "userid": "John992"
    },
    "data": [
        {
            "userid": "John993",
            "Key3": "Value3"
        },
        {
            "group2": [{
                "userid": "John994"
            }]
        }
    ],
    "Key1": "Value1",
    "Key2": "Value2"
}

The desired output should be:

{
    "group1": {
        "color": "red",
        "height": "100"
    },
    "data": [
        {
            "Key3": "Value3"
        },
        {
            "group2": [
                {}
            ]
        }
    ],
    "Key1": "Value1",
    "Key2": "Value2"
}

Thus far I have managed to parse the JSON and remove a specified element if it is found. However, my current code does not handle arrays or nested JSONs. The existing code snippet shown below solely removes instances of "userid":"John991".

 var b1 = JSON.parse(JSON);

 if (b1.hasOwnProperty("userid")){
    delete b1["userid"];
 }

Answer №1

To tackle this issue, you can develop a recursive function that iterates through the keys and removes the specified key. Here's an example:

const input = {
  "userId": "John991",
  "group1": {
      "color": "red",
      "height": "100",
      "userid": "John992"
  },
  "data": [
      {
          "userid": "John993",
          "Key3": "Value3"
      },
      {
          "group2": [{
              "userid": "John994"
          }]
      }
  ],
  "Key1": "Value1",
  "Key2": "Value2"
};


function deleteKey(obj, keyToDelete) {
  Object.keys(obj).forEach(key => {
    if (key.toLowerCase() === keyToDelete) {
      delete obj[key];
    }
    value = obj[key];
    if (value instanceof Object) {
      deleteKey(value, keyToDelete);
    }
  });
}
deleteKey(input, "userid");

console.log(JSON.stringify(input, null, 2));

Answer №2

Check out this custom function:

const jsonObj = {
  "userID": "John991",
  "group1": {
    "color": "red",
    "userid": "John992",
    "height": "100"
  },
  "data": [{
      "userid": "John993",
      "Key3": "Value3"
    },
    {
      "group2": [{
        "userid": "John994"
      }]
    }
  ],
  "Key1": "Value1",
  "Key2": "Value2"
}

function removeProperty(obj, prop) {
  let jsonString = JSON.stringify(obj);
  const regex = new RegExp(`,?"${prop}":".*?",?`, "gi");
  jsonString = jsonString.replace(regex, '');
  jsonString = jsonString.replace(/""/, '","');
  return JSON.parse(jsonString);
}

const updatedObj = removeProperty(jsonObj, "userID")
console.log(updatedObj)

The removeProperty function stringifies the given object, performs text replacement, and then parses the modified text back into an object. It replaces all occurrences of the specified property along with its value, accounting for different placements within the object.

The regular expression used in text replacement eliminates the property and its value, including leading and trailing commas. In cases where the property is sandwiched between other properties, a comma is added to maintain proper object structure.

This regex manipulation leverages the power of regular expressions. More information on regex can be found at .

Additionally, I included the /i/ flag in the regex pattern since your object contains variations like "userId" and "userid", ensuring both are removed as intended.

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

How can I search and sort on a custom formatted column using the jqGrid toolbar search functionality?

UPDATE : I finally figured it out, solution below I've been trying to find a solution to my problem by looking at other questions without success. I am loading jqGrid with json data. Here's an example of the json file : {"status" : &q ...

React-redux: Data of the user is not being stored in redux post-login

Hello everyone, I am fairly new to using react-redux and I'm currently facing an issue with storing user information in the redux store after a user logs in. I am utilizing a django backend for this purpose. When I console out the user in app.js, it ...

Why does i18next only function on http://localhost:3000/de (landing page) in NextJS and not on http://localhost:3000/de/about?

I'm new to this and feeling lost on how to tackle this issue. I tried following the instructions on https://github.com/i18next/next-i18next, but I'm struggling with index.js. When I toggle /de on my landing page, it translates correctly in the UR ...

Retrieving JSON array data in Android via a URL getPath

I am new to Android app development and currently working on an app that displays information about items in the game Guild Wars 2. You can find the data here. My goal is to read the entire list of items including their name, price, and icon, and display t ...

Choosing the state object name dynamically within a React JS component

I have a quick question about updating state in React. How can I change a specific object in a copy of the state that is selected using e.target.name and then set to e.target.value? For example, if I want to change newState.age when e.target.name = age i ...

Incomplete Loading of Google Maps

Let me clarify that the solutions I have come across so far have not been successful. I am attempting to display a modal alert with a basic Google Maps integration. Problem: Google Maps does not load completely. Snippet from my .js file: var map; functi ...

javascript: verify the presence of uppercase and lowercase letters

Can the validation of at least 2 lowercase and 2 uppercase letters be implemented when checking the case? Below is the condition I am currently using. function HasMixedCase(passwd){ if(passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) return true ...

Issues with data retrieval from PHP file in AJAX submission

During my attempts to utilize AJAX for submitting data to a PHP file, I encountered an issue where the submission was successful and I could receive a message echoed back from the PHP file. However, when trying to echo back the submitted data or confirm if ...

Implementing momentLocalizer with moment.js in react-big-calendar alongside fullcalendar.js

I'm currently working with react-big-calendar and I require assistance in setting up localization as per the example provided on GitHub. import BigCalendar from 'react-big-calendar'; import moment from 'moment'; BigCalendar.setLo ...

The value in a JSON can alternate between being a string or an object at times

I am facing a challenge with JSON data that can have two different formats. In one format, the location value is a string, while in the other format it is an object. Here is an example of the first format: { "result": [ { "upon_approval": "Pro ...

The array is coming back empty after attempting to add objects to it

My Node JS and Express JS controller code is below: const UserComment = require(".../model/UserComment"); router.post("/get/comments", async (req, res) =>{ try{ let currentUserID = req.body.userID; let myUserComment = await UserComment.find({userID: cu ...

Soft keyboard on mobile fails to update when arrows are used in Ajax-populated dropdown menus

I am working on a web form that includes two select fields: Country and City: <select id="country" onchange="getCity(this);"> <option value="">-- Please select your country --</option> <option value="1">Austria& ...

JavaScript and AJAX are showing an error message that says: "ReferenceError: x is not

I am currently working on a jQuery function that retrieves the value from a PHP-generated checkbox and sends it through AJAX. The value being sent is always a single word consisting only of letters. Here is the script I have written: <script type="text ...

Mystery of the Unresponsive MD Ripple Button

While working on creating a CSS button, I wanted to incorporate the Material Design ripple or wave effect into it. I came across a simple script on codepen that works well by adding the class "ripple" to various elements such as divs, buttons, images, and ...

Retrieve the original jqXHR object from the success callback of the $.ajax function

My original task is as follows: Execute a jQuery.ajax() request. Upon success, perform additional checks on the data received from the server. If these checks fail, reject the promise for further handling. After researching extensively online, I came up ...

The left join in D3 mapping is causing an issue as it is returning null values, which is halting the progression of the data processing for the next steps

Currently, I am working on D3 state-level mapping. While processing the data, I encountered an issue. The map data is structured as follows (dat1.ndjson): {state: a, code: aa} {state: b, code: bb} {state: c, code: cc} However, not all information is comp ...

Even though I am aware that the variable AJAX is attempting to return is not empty, it is still returning 'undefined'

I wrote a basic PHP script that retrieves information from a database and stores it in a multidimensional array: <?php //PHP code to fetch data from DB error_reporting(E_ALL); $db = new mysqli("localhost","root","pass", "Media") ...

Tips on effectively organizing information retrieved from an XML file?

I would like to organize the data in ascending order based on the DATE after making this ajax call function parseXML(xml){ var weatherArray = []; var weatherElement = xml.getElementsByTagName("forecast")[0]; weatherArray.queryTime = weatherEl ...

Utilize a jQuery selector to target the initial element of every alphabet character

I'm seeking some assistance with jQuery selectors and have a specific scenario that I need help with. Here is the HTML structure I am working with: <ul> <li class="ln-a"></li> <li class="ln-b"></li> <li cl ...

Begin a new countdown timer upon clicking the next button

Currently, I am developing a bid auction website and I have implemented a countdown timer script. The timer works perfectly on the initial window load. However, when I click on the restart button, it fails to reset the countdown timer to a new value. < ...