2

I have a JSON object.
I need to change values of all occurrences of a given field of it.
For example:

{
  email:"aaa@bbb.com",
  person: {  
    email:"dfd@ffds.com"  
  },  
  mother: {  
    name: "AAA",  
    email:"fdsfd@fdsfsd.com",  
    friend: {  
      email:"fdsd@gfsgf.com"  
    }
  }  
 } 

I need to find all emailfields and change their values based on their values.

I know how to iterate through one level of a JSON, I do not know how to iterate through all levels.

Thank you! :-)

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Jacek Wojcik
  • 1,223
  • 2
  • 19
  • 33

2 Answers2

3

First of all this is not a JSON object, it is a simple JavaScript object.

Then you can use recursion to loop through all the object levels, and check if the iterated property holds an object so process it again otherwise if it's email so change it.

function process(obj) {
  for (var key in obj) {
    if (typeof obj[key] == 'object') {
      process(obj[key]);
    } else if (key == "email") {
      obj[key] = "new email value";
    }
  }
}

Note:

I used the string "new email value" as new value for email, but you can change it accordingly with your desired value.

Demo:

var data = {
  email: "aaa@bbb.com",
  person: {
    email: "dfd@ffds.com"
  },
  mother: {
    name: "AAA",
    email: "fdsfd@fdsfsd.com",
    friend: {
      email: "fdsd@gfsgf.com"
    }
  }
}

function process(obj) {
  for (var key in obj) {
    if (typeof obj[key] == 'object') {
      process(obj[key]);
    } else if (key == "email") {
      obj[key] = "new email value";
    }
  }
}
process(data);
console.log(data);
StudioTime
  • 22,603
  • 38
  • 120
  • 207
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
1

Use the same style recursive function as in my answer here, just modify it slightly:

function changeEmail(obj, newEmail) {
  Object.keys(obj).forEach(key => {
    if (key == "email") {
      obj[key] = newEmail;
    }
    if (typeof obj[key] == "object") {
      changeEmail(obj[key], newEmail);
    }
  });
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79