Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript replace all occurrences in JSON only for a given key

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’).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading