javascript-多级对象-基于键的破坏性合并
作者:互联网
我有两个对象.基本上是模型和数据情况.无法弄清楚如何递归删除数据对象中已从模型中删除的项目.
首先是模型:
var foo = {
"title": "Enter title",
"info": {
"released": "Enter year",
"runtime": "Enter time"
}
}
另一个是数据:
var bar = {
"title": "Forrest Gump",
"info": {
"released": "1994",
"runtime": "02:22",
"awards": "3"
}
"genre": "Drama/Comedy-drama"
}
我正在尝试在两个对象之间进行通用比较,从而导致:
var bar = {
"title": "Forrest Gump",
"info": {
"released": "1994",
"runtime": "02:22"
}
}
任何帮助将不胜感激!
如果能够添加存在于蓝图中但不存在于数据中的对象键值,那将是一个超级好处.我有单独工作,但这将是一个不错的奖励!
解决方法:
Object.keys上的递归函数应该可以正常工作:
var foo = {
"title": "Enter title",
"info": {
"released": "Enter year",
"runtime": "Enter time"
}
};
var bar = {
"title": "Forrest Gump",
"info": {
"released": "1994",
"runtime": "02:22",
"awards": "3"
},
"genre": "Drama/Comedy-drama"
}
function getBoth(base, data) {
var result = {};
Object.keys(base).forEach(key => {
if (typeof base[key] == "object" && data[key]) {
result[key] = getBoth(base[key], data[key]);
} else if (data[key]) {
result[key] = data[key];
}
});
return result;
}
console.log(getBoth(foo, bar));
标签:javascript-objects,lodash,javascript,object 来源: https://codeday.me/bug/20191024/1922728.html