0

Problem: Create a javascript function that takes an object (of any size and depth), iterates through it and runs some basic string replacing on any strings and returns the object with the amended values.

I have two ideas about the implementaion, but cannot get a solution for either:

var context = {
"test1": "123",
"test2": "123",
"test2.2": "123",
"test3": {
    "test4": "cats",
    "test5": {
        "test6": "test1",
        "test123": "1231232"
    }
}
};

Idea 1)

Loop the array, and change the values,

http://php.net/manual/en/language.references.pass.php

In some way similar to PHP

Idea 2)

Build an array of path(s) to the object, so to replace the "test123" value I can create such an array:

['test3', 'test5', 'test123']

... this part is simple, but how do I then convert this to something like:

context['test3']['test5']['test123'] ?

Thankyou in advance.

loujaybee
  • 96
  • 2
  • 6

1 Answers1

1

Loop over the object and invoke the function recursively if the value at hand is an object. In pseudocode:

function replaceInObject ( obj, find, repl)

    for key in obj

       value = obj[key]
       if value is object
           obj[key] = replaceInObject(value, find, repl)
       else
           obj[key] = value.replace(find, repl)

   return obj
georg
  • 211,518
  • 52
  • 313
  • 390