What is the best way to loop through arrays of objects within other arrays and delete specific attributes?

I have an array of JavaScript objects with potential children who share the same type as their parent. These children can also have their own set of children. My goal is to loop through all nodes and modify certain values.

[
    {
        "text": "Auto",
        "icon": "/libs/jstree/folder.png",
        "state": {
            "opened": true,
            "selected": true
        }
    },
    ...

Within the given object, I aim to iterate through all nodes and delete the "state" attribute. How should I go about this process?

Answer №1

One way to remove states recursively is by checking both inside and outside.

Check out this recursive method here

function removeStateFromObject(obj){
    if (obj.hasOwnProperty('state')) delete obj['state'];
    if (obj instanceof Array) obj.forEach(removeStateFromObject);
    else if (obj instanceof Object) for (var key in obj) removeStateFromObject(obj[key]);                 
}

Answer №2

Check out this solution:

function eliminateKeys(data, targetKey) {
    data.forEach(function(item, idx) {
        delete item[targetKey];
        if (item.children !== undefined) {
            eliminateKeys(item.children, targetKey);
        }
    });
}

eliminateKeys(jsonData, "status");

Live example: http://jsfiddle.net/4dhJ5N68/

Answer №3

To effectively navigate through nested objects, it is crucial to employ a recursive function. Below is an example of a common approach to iterating over nested objects:

function traverse(obj){
    for(key in obj){
        console.log(obj[key]);
        if(typeof obj[key] === "object"){ 
            traverse(obj[key]); 
        }
    }
}

You can build upon this function to tailor it to your specific requirements. If you are utilizing JQuery, they offer the .each(function(index, item){}) method which serves a similar purpose.

If you need assistance with anything else, feel free to update your post or leave a comment below.

Answer №4

To achieve this in a different way, utilize the replacer parameter within the JSON.stringify function like so:

JSON.parse(JSON.stringify(object, ['text', 'icon', 'children']))

By providing a list of specific properties to include in the output, other properties such as state will be excluded from the result. More information can be found in this example with an array.

Answer №5

Why not give this a shot:

jQuery.each(myJSONObject, function(i, val) {
    delete val.state;
});

Check out the Fiddle here

Update available:

Here's another solution that requires a temporary variable.

var tempJsonObject = [];
jQuery.each(myJSONObject, function(i, val) {
    delete val.state;
    tempJsonObject[i] = val;
});

myJSONObject = tempJsonObject;

See the updated Fiddle here

Update:

This update includes removing the state property from child objects as well.

removeProperty(myJSONObject, "state");

function removeProperty(myJSONObject, prop) {
    jQuery.each(myJSONObject, function(i, val) {
        delete val.state;

        if(val.hasOwnProperty("children")) {
          removeProperty(val.children, "state");
        }
    });
}

View the latest version of the Fiddle here

Answer №6

let parsedJSON = JSON.parse(data);
for (let key in parsedJSON) {
   console.log(parsedJSON[key].content);
   parsedJSON[key].content = "updated text"
   let innerData = parsedJSON[key].children
   for (let j in innerData) {
       console.log(innerData[j].content);
       innerData[j].content = "new text for all inner elements"
   }
};

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

Disabling the Bootstrap tooltip feature is a quick and easy process

Is there a way to turn off bootstrap tooltip on my website? I activated it with the code below: function activateTooltip() { const toolTips = document.querySelectorAll('.tooltip'); toolTips.forEach(t => { new bootstrap.Tooltip(t); } ...

Notification does not appear once the full content of all iframes on the page has been loaded

<!DOCTYPE html> <html lang="en"> <head> <title> </title> <meta charset="utf-8" /> <link rel="stylesheet" type="text/css" href="css/custom.css" /> </head> <bo ...

Determine the number of distinct elements in fields using MongoDB aggregation

After executing my query, I received documents in the following format: { _id: '48nmqsyxmswpkkded2ac_331fabf34fcd3935', actions: { sales: { pixel: [Object] } }, date: Sun Jul 27 2014 00:00:00 GMT-0400 (EDT), client: '48nmqsyxmswpkkded ...

The objects-to-csv module encountered an error: fs.existsSync is not a valid function for this

"TypeError: fs.existsSync is not a function" Whenever I try to create a CSV file and input some data into it, this error message pops up. const objectstocsv = require('objects-to-csv'); export default { data () { return { ...

When using ViewBag in JavaScript, an error may occur with the message "Uncaught SyntaxError: Unexpected token '<'"

When I try to fetch data from an API and assign it to the VIEW BAG, I encounter an error during runtime. List<DevInfo> DevList = await RestApi.Instance.GetAllDevAsync(); var nameT = DevList.Select(a=>a.Name).ToList(); ViewBag.datasourceDevList = n ...

Problem with jQuery form button in dynamic table detecting rows after the first

I am currently working on a file that generates a dynamic table based on the records in a database. Each row in the table has a button to delete that particular row. The code I have written works perfectly for the first row, but it fails to detect the row ...

What steps should be taken to generate a successful pop-up window post registration in PHP?

beginning section continuation What is the best way to design an effective popup window? ...

"Exploring the process of looping through a JSON object following an asynchronous retrieval of JSON data using

I am facing an issue while trying to iterate through a JSON object in jQuery after fetching it asynchronously. I have a function called 'listFiles' that uses async to successfully retrieve a file list from a directory (dir) by calling an API endp ...

Escape a "for" loop from within a callback function in Node.js

My objective with the code snippet below is to exit FOR LOOP B and continue with FOR LOOP A by utilizing a callback function. for(var a of arrA) { // ... // ... for(var b of arrB) { // ... // ... PartService.getPart(a ...

Node.js encountering an empty array from an API request

In the 'product.js' file, there seems to be an issue with the API call '/achaar/products/1'. The value of val is empty when logging it in the console. Other API calls like '/achaar/products' are functioning correctly, but spec ...

Iterate through a jQuery function to retrieve values from checkboxes starting from the 4th one that has been clicked

I am currently using a loop in a form to calculate the total price of a product based on user selections. However, I have encountered a challenging task where certain checkbox groups have specific rules. For instance, group A should only contribute to the ...

develop a submission form using jquery

I am looking to create a submit action where clicking the submit button does not refresh the page. Instead, the data inputted in div1 will be sent to kanjiconverter.php and displayed in div2 using <?php echo $newkanji ?>. There are three forms on thi ...

The Angular directive ng-model is not able to return a value

I'm currently troubleshooting an issue with the filters in an older project. Here's the HTML snippet: <input type="text" class="form-control" ng-model="FilterEventsEdit" ng-change="FilterEvents()" ...

Keep your filter content up-to-date with real-time updates in Vue.js

I am facing an issue with a markdown filter where the content of component.doc is set to update through a websocket. Despite updating the scope's component, the filtered content remains unchanged. Is there a way to dynamically refresh the v-html in t ...

Angular JS Tutorial: How to Nest ng-views

When merging two separate Angular apps into one, I encountered the need to nest ng-views. The structure of my sample code (index.html) looks like this: <!doctype html> <html lang="en" ng-app="myApp"> <head> <meta ch ...

Unexpected error occurred when attempting to fetch the jQuery value of the radio button: "Unrecognized expression syntax error"

I am facing an issue while trying to extract the value of a radio button using $("input[@name=login]"); I keep getting an "Uncaught Syntax error, unrecognized expression" message. To view the problem, visit http://jsfiddle.net/fwnUm/. Below is the complet ...

"Array.Find function encounters issues when unable to locate a specific string within the Array

Currently, I am utilizing an array.find function to search for the BreakdownPalletID when the itemScan value matches a SKU in the array. However, if there is no match found, my application throws a 'Cannot read property breakdownPalletID of undefined& ...

The Philosophy Behind Structuring Node.js Modules

There appears to be a common understanding regarding the directory structure in node.js, but I have not come across any official documentation on this topic. Based on my exploration of open source projects, it seems that most projects typically include a ...

Cannot locate JSON file in NodeJS

Currently, I am developing an express API and looking to establish a connection with a MySQL server using this API. The configuration settings are stored in a file named settings.json. To retrieve these settings, I am utilizing the following code: const c ...

An npm list is always full of modules

As I prepare to install a package using npm, I noticed that my folder for the new project already has numerous items listed when I run npm list. Is it normal for the folder not to be empty at this stage? Have I made an error somewhere? ...