Gopesh Gopesh - 7 months ago 29
JSON Question

Recursive Object mapping in javascript

I am trying to map an object from another object in JavaScript. Like

var requestObj = {
id: "",
name: "",
age: "",
obj: {
id: ""
}
};

var processedObj = {
id: 10,
name: "John Doe",
age: 20,
family: true,
obj: {
id: 100,
text: "Obj Desc"
}
};


if i call a method like

format(requestObj, processedObj);


i need to get the output as

{
id: 10,
name: "John Doe",
age: 20,
obj: {
id: 100
}


Working Fiddle

Everything is working fine if there is no inner objects. I have done a recursive method but it is not working as expected.Please have a look on it

Answer Source

A few things needs correction in your original code, when you were calling format() function recursively you were not assigning the results returned from the function. Also arguments to format() function seemed incorrect to me.

I've modified your code a bit. And it outputs your desired format.

var requestObj = {
  id: "",
  name: "",
  age: "",
  obj: {
    id: ""
  }
};

var processedObj = {
  id: 10,
  name: "John Doe",
  age: 20,
  family: true,
  obj: {
    id: 100,
    text: "Obj Desc"
  }
};


format(requestObj, processedObj);

function format(requestObj, processedObj) {
  for (var keys in processedObj) {

    if (requestObj.hasOwnProperty(keys)) {
      if (typeof processedObj[keys] == 'object') {
        requestObj[keys] = format(requestObj[keys], processedObj[keys]);
      } else {
        requestObj[keys] = processedObj[keys];
      }


    }
  }
  return requestObj;
}

console.log(requestObj)