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 are no inner objects. I created a recursive method but it is not working as expected. Please have a look at it.
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 are no inner objects. I created a recursive method but it is not working as expected. Please have a look at it.
Share edited Feb 13, 2023 at 12:24 kahlan88 1011 silver badge8 bronze badges asked May 12, 2017 at 6:46 GopeshGopesh 3,95011 gold badges39 silver badges53 bronze badges1 Answer
Reset to default 6A 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)