What is the best way to apply a function to every value of a property within a javascript object?

I have an object structured like this. It will continue with more children blocks in a similar format. My goal is to replace the value of "date" throughout the entire object with a version processed through NLP.

{
"date": "next friday"
"more text": "someVariable"
"children": [{
    "date": "today"
    "more text": "someVariable"
    "children": [{
        "date": "yesterday"
        "more text": "someVariable"
        "children": []}, 
        {"date": "yesterday"
        "more text": "someVariable"
        "children": []}] 
}
}

My aim is to run a text replacement function solely on the values of "date" within the entire array and return an updated object where everything else remains unchanged, except for the "date" values that successfully undergo the find and replace operation.

This essentially involves applying NLP to the "date" items.

I've made an attempt using a recursive function but I'm struggling to preserve the original structure.

async function parseChildren(obj, child = true){
    for (var k in obj)
    {if (obj[k] !== null){
        // console.log(obj(k))
        if (k == "date"){
            console.log(obj[k])
            console.log(parseDates(obj[k]))
        }
        if (k == "children"){
            parseChildren(obj[k], false)
        }
        else if (child == false) {
        parseChildren(obj[k])
        }
        
    }
}
}

Any assistance you can provide would be greatly appreciated!

Answer №1

One possible approach is as follows:

const test = {
    "date": "next friday",
    "more text": "someVariable",
    "children": [{
        "date": "today",
        "more text": "someVariable",
        "children": [{
            "date": "yesterday",
            "more text": "someVariable",
            "children": []}, 
            {"date": "yesterday",
            "more text": "someVariable",
            "children": []}] 
    }]
}

function mutateDates(obj){
    if (obj.date) {
        obj.date = 'new_mutation_here'
    }

    obj.children.map(mutateDates)
}

mutateDates(test)

This will lead to the desired output:

{
    "date": "new_mutation_here",
    "more text": "someVariable",
    "children": [{
        "date": "new_mutation_here",
        "more text": "someVariable",
        "children": [{
            "date": "new_mutation_here",
            "more text": "someVariable",
            "children": []
        }, {
            "date": "new_mutation_here",
            "more text": "someVariable",
            "children": []
        }]
    }]
}

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

What is the method for subtracting pixels from a percentage value?

Is there a way to accomplish a similar effect to this: height: calc(100% - 50px); height: -webkit-calc(100% - 50px); height: -moz-calc(100% - 50px); In browsers that do not support these properties? I have a responsive div with two children. The height ...

Ways to extract information immediately after using the .load method

Is there a way to instantly store data from .load in JavaScript? Whenever I use .load within a JavaScript function to retrieve content from the server and display it on the browser page, the content does not update immediately. It's only when the fu ...

Retrieve a JSON file with Hebrew data from a server and then interpret it using Node.js

I have a JSON file with dynamic content stored on a remote server acting as an API. The file also includes Hebrew text in its values. How can I retrieve the response and convert it into a JSON object? Here is the code snippet I have put together using Re ...

"Creating a delay within a loop using the setTimeout function

When using setTimeout in a loop, I noticed that all the operations are executed only after the loop ends. I followed the advice from multiple articles and tried putting setTimeout in a separate function, but it didn't make any difference. Here is the ...

How can you make sure that VS Code always utilizes relative paths for auto imports in TypeScript?

VS Code has been automatically importing everything using Node-like non-relative paths relative to baseUrl, which is not the desired behavior. Is there a way to instruct VS Code to import everything with relative paths, excluding Node modules? Removing t ...

Upon clicking the "show more information" button on the page, JavaScript executes the function to display additional details

<a href="#" class="button">Read More</a><br> I'm currently struggling with programming a button on my website. Specifically, I need the Read More button to display all information related to the CDs I have for sale when clicked. A ...

Retrieve the selected value from a radio button

I am attempting to display the chosen value in an input field when a radio button is selected. However, the functionality seems to be broken when I include bootstrap.min.js. You can find the code on JSFiddle. $('input:radio').click(function() ...

Struggling with updating an array in state using setState?

Currently, I am working on a React app that involves taking user input, filtering array data based on that input, and updating another field in the same data. However, I have encountered difficulties when trying to use setState to make these changes. Addit ...

Having trouble with deploying Node.js to Heroku? Feel like your 'git push her

After successfully running my app locally, I encountered an issue when trying to deploy it to Heroku. The deployment process just hangs indefinitely and only displays one public file on the website with an error message stating: "https://analogy-alley.hero ...

issue with accessing instant state modification via useEffect

I am currently learning about React Hooks While I try to render a list from an array and remove the first element on click, the state gets updated in the handleclick function but it doesn't render correctly export default function App() { const [na ...

How to maintain the previous position of Rzslider in Angular Js after selecting the date?

I am currently utilizing RZslider for date and time picking, but I am encountering repeated issues. As a newcomer to Rzlider and angularJs, I am struggling with some aspects. The slider is set to display the current time plus 4 hours and minus 4 hours. For ...

Passing data back from an asynchronous function to its parent function in Node.js

Exploring the world of asynchronous programming is a new adventure for me as I delve into implementing Twilio video calls through Node.js. I've been grappling with calling a server-side function that in turn invokes another asynchronous function retu ...

`Troubleshooting Three.js webglrenderer.render problem`

I am currently working on a website using three.js and Nuxt.js. However, I have encountered an issue when trying to implement the EffectComposer. The console is showing numerous warnings like: three.webglrenderer.render(): the rendertarget argument has be ...

What steps can I take to ensure my customized tab component can successfully pass an index to its children and effectively hide panes?

I'm currently working on developing a custom Tabs component to enhance my knowledge of React, but I seem to have hit a roadblock. The structure involves three key components that draw inspiration from Material-UI tabs: Tabs, Tab, and TabPane. Tabs.j ...

How is it possible that TypeScript does not provide a warning when a function is called with a different number of arguments than what is expected?

I am working on a vanilla JavaScript project in VS Code and have set up jsconfig.json. Here is an example of the code I am using: /** * @param {(arg: string) => void} nestedFunction */ function myFunction(nestedFunction) { // Some logic here } myFu ...

What is the best way to clear the values of multiple chosen-select boxes in one go?

I am encountering an issue while using a chosen-select plugin. I have multiple select boxes created with JavaScript code. My goal is to reset all select boxes when I change the class to "default-chosen", but instead of displaying my message "not chosen," i ...

Tailor TypeScript to support various JavaScript versions

One of the advantages of TypeScript is the ability to target different versions of Javascript globally - allowing for seamless switching between transpiling ES3, ES5, or ES6. For browsers like IE that require ES3 support, it serves as the lowest common de ...

Obtaining values from multi-dimensional arrays with JavaScript and node.js

I have a data structure like this: let arr = [ ['animal','lion'], ['plant','rose'], ['tree','coconut'], ] I want to reformat it to look like this: ['animal','lion' ...

Looking to send information to a different website and get the response back using JavaScript?

Seeking assistance: I'm attempting to post my University seat number, 1da07cs102, to http://results.vtu.ac.in/results.php. This website uses rid as a name in form. How can I use JavaScript to retrieve my results from the specified site and display the ...

Utilizing Props to Manage State within Child Components

Is it possible to assign the props received from a Parent Component as the state of a Component? export default class SomeComp extends Component { constructor(props) { super(props); this.state = someProps; // <-- I want to set the ...