Home > OS >  How can I perform a function onto the value of each instance of a property in a javascript object?
How can I perform a function onto the value of each instance of a property in a javascript object?

Time:01-31

I've got an object like this. It'll continue in this format with more and more children blocks but this snippet gives an idea. I'm trying to replace the value of data, throughout this entire object with an NLP parsed version.

{
"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": []}] 
}
}

What I'd like to do is to run a text replace function onto only the values of "date" throughout the entire array and return a mutated object where everything remains the same except for the value of "date" whenever the find and replcae operation is successful.

I'm essentially running NLP on the value of item "date"

I've attempted a recursive function but can't figure out how to maintain 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])
        }
        
    }
}
}

Thank you in advance for any help!

CodePudding user response:

You could try something like this:

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 = 'mutation_here_we_it_is'
    }

    obj.children.map(mutateDates)
}

mutateDates(test)

This will result into:

{
    "date": "mutation_here_we_it_is",
    "more text": "someVariable",
    "children": [{
        "date": "mutation_here_we_it_is",
        "more text": "someVariable",
        "children": [{
            "date": "mutation_here_we_it_is",
            "more text": "someVariable",
            "children": []
        }, {
            "date": "mutation_here_we_it_is",
            "more text": "someVariable",
            "children": []
        }]
    }]
}
  •  Tags:  
  • Related