Change the names of all arrays within a complex nested structure containing multiple arrays

I'm currently working on a recursive "massage" function that requires me to rename specific property keys. So far, I've attempted various recursive methods but haven't had much luck.

One task is to eliminate the word 'Array' from all arrays nested within a deeply nested object.

Here is an example input:

var data = {
  test: {
    testArray1: [
      {
        testArray2: [
          {
            sample: {
              testArray3: [],
            },
          },
        ],
      },
    ],
  },
};

The desired output should look like this:

var result = {
  test: {
    test1: [
      {
        test2: [
          {
            sample: {
              test3: [],
            },
          },
        ],
      },
    ],
  },
};

Answer №1

A recommended strategy for handling this issue (excluding recursion) involves first converting the JSON data into a string using JSON.stringify(), performing necessary operations with replace() on the resulting string, and then transforming it back to JSON format with JSON.parse(). Here's an example:

const input = {
  test: {testArray1: [
    {testArray2: [
      {sample: {testArray3: ["Array"],},},
    ],},
  ],},
};

let res = JSON.stringify(input).replace(/(Array)([^:]*):/g, "$2:");
res =  JSON.parse(res);
console.log(res);

Answer №2

Below is a straightforward recursive method that should suit your needs:

function deleteWord(input, word = "Array") {

  if (Array.isArray(input)) {
    return input.map(obj => deleteWord(obj, word));
  } else if (typeof input == "object") {
    var result = {};
    Object.keys(input).forEach(key => {
        result[key.replace(word, "")] = deleteWord(input[key]);
    });
    return result;
  } else {
    return input;
  }

}

It's important to note that this solution may not be very reliable and could use up a lot of memory if dealing with a deeply nested object.

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

Having difficulty retrieving items from Mongoose-Node database

I am currently working with a Mongodb database that stores resume objects. These objects contain various skills information and I have set up a node-express server to query the database based on specific skills. For example, when querying for a skill like ...

Search and extract JSON data in MySQL

Currently, I am inputting JSON objects into a MySQL Database and then executing queries on them. Within the database is a table structured as follows: subjects | ----------------------------------------------- ...

Wondering how to optimize FullCalendar for mobile and touch events?

I am looking to incorporate a drop event feature into the mobile version of fullcalendar. To achieve this, I am utilizing Jquery UI Touch Punch. After researching on various platforms such as Stack Overflow 1, Stack Overflow 2, Stack Overflow 3, Stack Ove ...

Fixing errors with observables in an Angular 2 project using Rx

var foo = Observable.create(function(observer){ try{ console.log('hey there'); observer.next(22); throw new Error('not good at all'); setTimeout(function(){ observe ...

Unable to preventDefault() function from working within .then method

Snippet: angular .module('mean-starter') .run(run) ; function run($rootScope, Auth, $state) { function stopStateChange (message, event, redirect) { console.log(event); event.preventDefault(); alert(message); if (redirect) ...

Unable to get Discord.js sample code functioning correctly

Despite my best efforts, I can't seem to figure out why this simple example code is not working. As a newcomer to Java Script, I am struggling with understanding why the line GatewayIntentBits.Guilds is causing an error. Surprisingly, when I comment o ...

Error occurs in Selenium when a button is clicked: ".MoveTargetOutOfBoundsException"

In my project using Safari and Python with Selenium, I encountered an issue while trying to create a Python Selenium program that clicks on a 'confirm' button within an iframe. Despite the button and the iframe being in the viewport, the program ...

Unable to use addEventListener on media queries exceeding 768px

When testing the site on Firefox 49 and Chrome 63, I encountered the same issue. Clicking on each card worked fine on iPhone4, Galaxy 5, and iPhone 8 using Chrome. However, after switching orientations from 640px to 320px portrait view, the top card would ...

When utilizing the useLocation feature of React-Router-DOM to retrieve data passed in React, it can cause manually inputted links to malfunction

When manually inputting a link that is incorrect (e.g., "/characters/test"), it initially works fine, but if the link is correct, it still redirects to error 404. However, clicking the link from the Character component functions properly. This me ...

Displaying a loading spinner image as PHP script runs

Hey there! I've been experimenting with using a script to show a loading bar while my PHP code is running. I followed the instructions on this website, but even after following the exact steps, my loading bar still isn't showing up. Any suggestio ...

SQL's recursive capabilities allow for powerful data manipulation and querying

I am working with a series of tables structured as shown below: cables: id (integer) | name (char) knots: id (integer) | name (char) cableKnotAttachments: id (integer) | sourceCableId (integer) | targetKnotId (integer) cableCableAttachments: id (intege ...

`Error encountered when attempting to use the if else route on ajax data`

Within the given JavaScript code snippet, the like_add function is following the else route instead of the expected if route, even though it receives a success response. I am curious as to why this is happening. The data returns success, but instead of m ...

Execute the controller function with the value as a parameter

I encountered an issue while attempting to call a function in the c# controller and passing a value. The error message I received was: `'Unable to get property 'then' of undefined or null reference'. I also included the Driver Model but ...

IE encountered an invalid character

While working on a JavaScript function, I encountered an issue with a string variable. Specifically, when running the page in IE with this script, I receive an error message indicating an invalid character at the following line: let displayString = `${s ...

Utilizing TypeScript to enhance method proxying

I'm currently in the process of converting my JavaScript project to TypeScript, but I've hit a roadblock with an unresolved TypeScript error (TS2339). Within my code base, I have a class defined like this: export const devtoolsBackgroundScriptCl ...

Utilizing arrays in JavaScript alongside jQuery's methods such as $.inArray() and .splice()

I am currently dealing with an array that is limited to containing 12 values, ranging from 1 to 12. These values can be in any order within the array. My task is to iterate through the array and identify the first unused value, assigning it to a variable. ...

"Creating the Perfect Parallax Effect: A Step-by-Step

Seeking to implement a responsive parallax effect on my website, I have the following structure: <section id="first"> <div class="text fixed" > <h1><b>aSs</b> lorem ipsum dolor sit amet</h1> <p> ...

"Error encountered when trying to remove element from array: IndexOutOfBoundsException

I am encountering an issue when attempting to remove an item from an array, which is resulting in an IndexOutOfBoundsException if the item is present in the array. Although a similar question was raised in the comments, my query is specific to why this er ...

Is it possible to retrieve the `arguments` objects if one of the parameters is named "arguments"?

This code snippet will output 1: (function (params) { console.log(params); }(1, 2)); The params object has replaced the default arguments. Can we retrieve the original arguments object within the function's scope? ...

Move each four-character IT value to a new line

const maxNumLength = 4; event = jQuery.Event("keypress") event.which = 13 $('#input').on('input focus keydown keyup', function() { const inputValue = $(this).val(); const linesArray = inputValue.split(/(&bsol ...