Exploring nested arrays to make data modifications

Given the structure above, each type currently has text-1.

I am looking to change only the first occurrence to text-1, while the rest should be changed to text-2 in the data structure.

The order of the blocks must remain the same and different types within a block should not be affected.

I have attempted to loop through each block, but I'm struggling with the logic to modify only the first occurrence. Please assist.

Below is my current attempt:

let newData = data.forEach(data => {
  return data.block.forEach(block => {
    return block.child.forEach((type, i) => {
      if (i === 0) { return }
      type.type = 'text-2'
    })
  });
});

Current Data

const data = [
  {
    block: [
      { child: [{ type: 'text-1' }] },
      { child: [{ type: 'any type' }] },
      { child: [{ type: 'text-1' }] }
    ]
  },
  {
    block: [
      { child: [{ type: 'text-1' }] },
      { child: [{ type: 'text-1' }] }
    ]
  }
]

Expected Data,

const data = [
  {
    block: [
      { child: [{ type: 'text-1' }] },
      { child: [{ type: 'any type' }] },
      { child: [{ type: 'text-2' }] }
    ]
  },
  {
    block: [
      { child: [{ type: 'text-2' }] },
      { child: [{ type: 'text-2' }] }
    ]
  }
]

Answer №1

To streamline the process, you can create a function that retrieves the first string and then uses another string for subsequent calls.

const
    getOnce = (first, other, used) => () => used ? other : (used = true, first);
    data = [{ block: [{ child: [{ type: 'text-1' }] }, { child: [{ type: 'any type' }] }, { child: [{ type: 'text-1' }] }] }, { block: [{ child: [{ type: 'text-1' }] }, { child: [{ type: 'text-1' }] }] }],
    type1 = 'text-1',
    type2 = 'text-2',
    getType = getOnce(type1, type2),
    result = data.map(
        ({ block }) => ({
            block: block.map(
                ({ child }) => ({
                    child: child.map(o => Object.assign({}, o, o.type === type1 && { type: getType() }))
                })
            )
        })
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

One way to approach this is by using the revival parameter with JSON.parse:

var found = 0, data = [{ block: [{ child: [{ type: 'text-1' }] }, { child: [{ type: 'any type' }] }, { child: [{ type: 'text-1' }] }] }, { block: [{ child: [{ type: 'text-1' }] }, { child: [{ type: 'text-1' }] }] }]

data = JSON.parse(JSON.stringify(data), 
              (key, val) => key == 'type' && val == 'text-1' && found++ ? 'text-2' : val)

console.log( data )


Another alternative is to mutate the data structure using for...of:

const data = [{ block: [{ child: [{ type: 'text-1' }] }, { child: [{ type: 'any type' }] }, { child: [{ type: 'text-1' }] }] }, { block: [{ child: [{ type: 'text-1' }] }, { child: [{ type: 'text-1' }] }] }];
let found = 0;

for (const item of data)
  for (const block of item.block)
    for (const child of block.child)
      if (child.type === 'text-1' && found++)
        child.type = 'text-2';

console.log( data );

Answer №3

Given the following assumptions:

  • The array structure follows the example provided.
  • Each data element is an object.
    • Every object includes a block property that is an array.
    • Each block element may have a type property.
  • You aim to modify the original array without creating a new copy (based on my understanding of the question, but I could be mistaken).

Here is a rather messy solution for making the necessary alterations.

It's worth noting that this kind of manipulation is unconventional and doesn't appear very logical; therefore, I strongly recommend considering alternative data structures.

Explanation of the code can be found directly within it.

const data = [
  {
    block: [
      { child: [{ type: 'text-1' }] },
      { child: [{ type: 'any type' }] },
      { child: [{ type: 'text-1' }] }
    ]
  },
  {
    block: [
      { child: [{ type: 'text-1' }] },
      { child: [{ type: 'text-1' }] }
    ]
  }
];

// This seems unreasonable.. oh well.
data.forEach((o, i) => {
  // Iterate through each element while keeping track of the index.
  if (i > 0) {
    // If it's not the first element, locate all elements with children, iterate through the children, and replace every instance of '1' with '2' in the type property.
    o.block.forEach(c => c.child && c.child.forEach(child => child.type = child.type.replace("1","2")));
  }
  else {
    // For the first element, find the last block containing children with a type of 'text-1'.
    const elems = o.block.filter(c => c.child && c.child.length && c.child.some(child => child.type === 'text-1'));
    const found = elems && elems.length && elems[elems.length - 1];
    // If found, update the value.
    if (found) found.child[0].type = found.child[0].type.replace("1","2");
  }
});

console.log(data);

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

Errors slipping through the cracks of Express middleware

When it comes to using express and typescript, I am attempting to create a middleware for error handling similar to Sentry. Below is the code snippet: const catchError = ( error: Error, req: Request, _res: Response, next: any ) => { console. ...

Utilizing a dropdown selection to trigger an IF statement in a function

I have an HTML code snippet as shown below: The value "Test" is just for my reference to ensure that the code is functioning properly :) <script> var tfa78 = document.getElementById("tfa_78").selvalue; if( tfa78 == "karte" ) { document.getEl ...

The Javascript function will keep on executing long after it has been invoked

I am currently facing an issue with calling a JavaScript function within an AJAX call. The progress function below is supposed to be executed every time the for loop runs. However, the problem is that although progress is being run as many times as the for ...

Top method for transforming an ArrayList containing characters into a String

Looking for an easy way to convert an ArrayList of Characters to a String? While searching for solutions, I came across a similar thread (Best way to convert an ArrayList to a string), but I'm hoping for a simpler method. I attempted the following: ...

An unanticipated error occurred at **** Unauthorized access when attempting to read **** location

I encountered an error message saying: "Unhandled exception at 0x00d23737 in Test.exe: 0xC0000005: Access violation reading location 0x8a8c0344" This issue arises when running the code snippet below: int main(int argc, char* argv[]) { string My_String_Arr ...

Transfer the export to a different file and update all the files that import it accordingly

Is there a way, particularly in Typescript, to seamlessly move an export statement like the one below to an existing file and automatically update all files that import it? export const MyVar = 3; In the case of refactoring using Right Click > Refactor ...

Experience an engaging and dynamic liquid metal orb using Three.js

As I dive into the world of JavaScript and experiment with Three.js, I came across a fascinating tutorial by Paul Lewis. He demonstrated how to create an interactive liquid metal ball with Three.js, similar to the one showcased at In an attempt to incorpo ...

Exploring the world of jQuery AJAX alongside Google's currency calculator

I'm currently working on a code that utilizes an AJAX call to access the Google currency calculator. The expected outcome is to receive a JSON array that can then be used to gather exchange rate data. Here is the link: http://www.google.com/ig/cal ...

Ionic4: the functionality of the searchbar results is not functioning correctly

I have integrated the ion-searchbar in my application to filter a list of customers based on their first name and/or last name. However, I am facing two major challenges: Challenge 1: The search bar currently only matches either the first name OR the last ...

What is the best way to import modules with the "@" symbol in their path when working with Node.js?

Situation In my VueJS project, I have created service modules for use with vue cli. My code makes use of the @ symbol to easily access files within the src folder: /* Inside someService.js */ import API from '@/services/APIService.js' Ch ...

Expanding a div's size with CSS to fill the remaining space

Here's the setup I'm working with: <div class="parent"> <div class="moverBoy"></div> <div class="smartBoy"></div> </div> The parent element is fixed at 100x20 indefinitely. moverBoy and smartBoy are al ...

Avoid accidental overwrites in localStorage using JavaScript

I've been working on a Vue project where I'm implementing a shopping cart feature. In this setup, when the user clicks on a button, the item details are stored in localStorage and then displayed in the shopping cart interface. However, I encount ...

Updating HTML content with Node JS using MYSQL data

Seeking Guidance on Updating HTML Data Using Node.js I am looking for a way to update the HTML data in my files using Node.js without the use of EJS or any view engine. My views folder contains .js files that return HTML, and I need to change the data fro ...

What is the best way to incorporate Instagram photos into a slideshow?

Currently, I am using the SliderPro Slider to create a slider that resembles the examples shown on this demo page. The HTML code for this setup looks like the following: <div id="example2" class="slider-pro"> <div class="sp-slides"> < ...

Having trouble displaying a pre-designed 3D model in three.js

I would greatly appreciate it if someone could provide an example and elaborate on how to render a 3D object using three.js or similar libraries. The model already exists, so the focus is solely on rendering it effectively. Can you please guide me throug ...

Ways to verify that Node JS has been successfully installed?

Just recently diving into the world of OSX and I decided to take a stab at installing Node JS through Terminal using a detailed tutorial. How can I verify that the installation of Node JS was successful? Are there any commands or user-friendly GUI interfac ...

Tips for retaining previous data while loading in React hooks

Just started using react hooks and built my initial component. Everything is functioning properly except for a flickering issue while the data is loading. Here is my component (a basic list of articles with previous/next pagination): function InfoFeed ({ l ...

Unable to transmit the error information to a response

Currently, I am in the process of making a POST request with a form-data type body. Within the body, there is specific data that can be found here: https://i.sstatic.net/XvRgJ.png In order to parse the data field (which is stringified JSON) in the body ...

Safari is showing an error stating that the object BlobConstructor is not a valid constructor

Encountering an issue in Safari on Windows 7 within this specific section '[object BlobConstructor]' is not a constructor (evaluating 'new Blob([data], {type: 'application/pdf'})') After trying the solution mentioned in Blob ...

Angular library is being excluded from the R.js optimizer process

I'm encountering difficulties when trying to optimize an Angular project with the r.js optimizer. Everything works smoothly when I use grunt-requirejs for optimization, but as soon as I attempt to exclude Angular from the build, I encounter an error ...