Javascript replace all occurrences in JSON only for a given key Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Javascript replace all occurrences in JSON only for a given key without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m looking for a way to replace a given string in a JSON by another string, but only for a certain key. For example, suppose I have the following JSON, data:

[
    {
        "name": "please, I said please",
        "title": "Test One",
        "more": [
            {
                "name": "another name",
                "title": "please write something"
            }
        ]
    },
    {
        "name": "testTwo",
        "title": "Test Two"
    },
    {
        "name": "testThree",
        "title": "Test Three"
    },
    {
        "name": "testFour",
        "title": "Test Four"
    }
]

Let’s say for example, I am looking to replace all occurrences of the word “please” by “could you”. In this example, I only want to replace whole words. Right now, I’ve got a working example which does this:

const wordToReplace = "please"

const jsonString = JSON.stringify(data)
const reg = new RegExp(`\b${wordToReplace}\b`, 'gi) // whole words only and case insensitive
const dataReplaced = jsonString.replace(reg, function () {
  return 'could you'
}

console.log(JSON.parse(dataReplaced))

Given the above code, the word ‘please’ will be replaced by ‘could you’ for all occurrences. However, I want to replace the words only if the key is “title”. Right now, it will replace it for any given key (for example, in the first instance where the key is ‘name’ and also ‘title’).

One more thing to note is that the JSON can have a varying amount of nested properties as you can see from the example. It’s not always the same nested objects within.

Also, the reason I’ve added a function in the replace method is because I wast trying out ways to specify a key.

Answer

I wont recommend using replace on a json converted to string.

Instead, I’d recursively loop through the array/objects and alter the value if needed

Simple example:

const data = [{"name": "please, I said please", "title": "Test One", "more": [{"name": "another name", "title": "please write something"} ] }, {"name": "testTwo", "title": "Test Two"}, {"name": "testThree", "title": "Test Three"}, {"name": "testFour", "title": "Test Four"} ];
const regx = new RegExp(`\bplease\b`, 'gi');

function replace(obj) {
    for (var k in obj) {
        if (typeof obj[k] == "object" && obj[k] !== null) {
            replace(obj[k]);
        } else if (k === 'title') {
            obj[k] = obj[k].replaceAll(regx, 'could you');
        }
    }
    return obj;
}

const result = data.map(o => replace(o));
console.log(result);
We are here to answer your question about Javascript replace all occurrences in JSON only for a given key - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji