Searching and replacing a string within the title key of a nested object in Vue.js

I need help with manipulating a nested object that contains multiple keys, where each key includes a title and children. The children array consists of objects with their own title and children keys, forming a tree structure. How can I efficiently search for and replace one word or part of a title's value within this nested structure?

const object = {
    id: 'uuid',
    title: 'hello You',
    type: number,
    visibility: true,
    children: [
        {
            id: 'uuid',
            title: 'You don't have any comments...',
            type: number,
            visibility: true,
            children: [{...}, {...}, ...],
            key1: {...},
            key2: [{...}]
        },
        {
            id: 'uuid',
            title: 'You your problem is not with json...',
            type: number,
            visibility: true,
            children: [{...}, {...}, ...],
            key1: {...},
            key2: [{...}]
       }
    ],
    key1: {...},
    key2: [{...}]
}

search you and replace world on title

output = {
    id: 'uuid',
    title: 'hello world',
    type: number,
    visibility: true,
    children: [
        {
            id: 'uuid',
            title: 'world don't have any comments...',
            type: number,
            visibility: true,
            children: [{...}, {...}, ...],
            key1: {...},
            key2: [{...}]
        },
        {
            id: 'uuid',
            title: 'world your problem is not with json...',
            type: number,
            visibility: true,
            children: [{...}, {...}, ...],
            key1: {...},
            key2: [{...}]
       }
    ],
    key1: {...},
    key2: [{...}]
}

Answer №1

If you want to discover a specific key within an array and search through its children as well, one effective approach is to utilize a recursive strategy.

function recursive (newArray) {
  newArray.map(obj => {
    if (obj.title) {
      obj.title = obj.title.replace(/You/g, 'world')
    }
    if (obj.children) {
      return recursive (obj.children)
    }
  })
  return newArray
}

To implement this function:

let arr = [object]

recursive(arr)

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

Seeking assistance with transmitting data to the server and retrieving it for use. I am looking to achieve this goal utilizing JavaScript with Node.js

I've been experiencing challenges with the interactions between front-end and back-end. I am confident that I am sending the data, but unfortunately, I am unable to access it afterwards. Recently, I utilized this code template (sourced from Mozilla&ap ...

Having trouble with the jQuery toggle functionality not working as expected

I'm implementing a function where a div should increase in height and opacity when clicked, and then revert back to its original state when clicked again. I used the toggle function for this purpose, but the issue is that the button disappears when th ...

Keep only certain fields and eliminate the rest

Write a function that filters out all fields except 'firstName' and 'lastName' from the objects. Check out this code snippet I came up with. Any feedback? let people = [ { firstName: 'John', lastName: &apo ...

Encountering difficulties with the functionality of Google Places API

I am attempting to incorporate the autocomplete functionality of Google Places API into a text field. Below is the code I have implemented: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script ...

Error: Undefined object while trying to access 'injection' property

After updating to React 16.x, I encountered the following error: Uncaught TypeError: Cannot read property 'injection' of undefined at injectTapEventPlugin (injectTapEventPlugin.js:23) at eval (index.js:53) at Object.<anonymous> ...

A Promise is automatically returned by async functions

async saveUserToDatabase(userData: IUser): Promise<User | null> { const { username, role, password, email } = userData; const newUser = new User(); newUser.username = username; newUser.role = role; newUser.pass ...

Creating a dynamic label in Echart with multiple values: A step-by-step guide

How can I customize the legend in an Echarts doughnut chart to display additional content like shown in the image below? Current Legend: [ Desired Legend: https://i.stack.imgur.com/ur0ri.png Thank you, Eric ...

What is the best way to prevent the collapse v-b-toggle event from being triggered by an

I am currently using a v-b-toggle to toggle another div on and off. However, within the div where the v-b-toggle is located, there is an input checkbox. The issue that I am facing is that when I click on this checkbox, the toggle functionality is activa ...

Displaying Grunt Command-Line Output in Browser

Is there a straightforward method to display the command-line output of a grunt task in a browser? Essentially, I want to showcase the input and/or output of a command line process within a browser window. While I am aware that I could develop a custom app ...

What is the best way to transfer data from one form to another HTML document?

My code is ... <form name="myForm" action="demo_form.html" onsubmit="return validateForm()" method="GET"> <input type="text" name="StuserID" id="basic" value="" placeholder="userID" /> <input type="submit" value="Login"/&g ...

Only if there is an update in the SQL database, I wish to refresh the div

I have created a voting system and I am facing an issue with the data updating. I have implemented a setInterval function in javascript to load the data every 2 seconds, but it's not working as expected. There are no errors shown, but the data is not ...

What might be causing the issue with the reload feature not functioning properly for a

I have attempted various codes, but none of them seem to work. My goal is to refresh only a specific section every 5 seconds without reloading the entire page. It is crucial not to refresh the whole page because there is a chat function involved, and users ...

Generate a sequence of years without relying on the range function

Is there a different approach to generating this array without relying on the range function? Below is an illustration of what I want, but without utilizing the range method. const years = myCustomArrayGeneration(1990, getYear(new Date()) + 1, 1); ...

Animation fails to initiate when the object enters the viewport

I attempted to inject some enchantment into my project by implementing code from a tutorial found on this CodePen. However, I encountered an issue where the code only functions properly within that specific CodePen environment. Even after copying the same ...

"Combining AngularJS with Material Design disrupts the functionality of infinite scroll

Issue: Infinite scroll is loading all pages at once instead of waiting for the user to scroll to the page bottom. Environment: AngularJS 1.3.17 Materials Design 0.10.0 Infinite scroll script: https://github.com/sroze/ngInfiniteScroll Demo being used: The ...

Utilizing a variable in Vue.js to set the background image in the style template

Is it possible to use a variable within the background-image of a style template? I am trying to achieve something like the following: <script> export default { name: 'setCss', computed: { cssVars() { var ua = navigato ...

How can I access multiple icons using jQuery?

Below is the JavaScript code I am using: $(document).ready(function() { $.getJSON("Stations.php", function(jsonData){ $.each(jsonData, function(key,value) { $('#selectStation') .append($("<option></option>") ...

unable to display loading image prior to upload

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html lang="en"> <head> <title>Unique Prints</title> <meta charset="utf-8"> <meta name="viewport" conte ...

Having issues with the closest method in DojoQuery on Internet Explorer

Looking for guidance on utilizing the closest method in Dojo to identify the first parent element of an element that needs to be displayed/hidden based on a selected value in a filtering select. It functions correctly in Firefox, but encounters an issue in ...

Selecting avatars using Nuxt and Vuetify for a personalized touch!

Having trouble getting an avatar picker to function properly... When I click to select the avatar, it's not being replaced, and I'm encountering the error TypeError: Cannot read property 'src' of undefined at VueComponent.selectAvatar ...