admin管理员组文章数量:1406966
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)
本文标签: arraysRecursive Object mapping in JavaScriptStack Overflow
版权声明:本文标题:arrays - Recursive Object mapping in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744951836a2634130.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论