让我们说这是我的api响应
user = {
profile: {
name: "John",
age: 32,
links: [
{
github: {
name: "John",
url: "https://github.com/john"
},
facebook: {
name: "John",
url: "https://facebook.com/john"
}
}
]
},
posts: [
{
id: 1,
title: "First post"
},
{
id: 2,
title: "Second post"
}
]
}
我的预定义对象结构是
predefinedUserObj = {
profile: {
name: "",
age: "",
links: [
{
github: {
name: "",
url: "",
},
facebook: {
name: "",
url: "",
}
}
]
},
posts: []
}
我从user object
获得了Api
,并且想将api响应与预定义的结构进行比较。
如果api响应中user.profile.links[0].github
的值为null
,那么我想将预定义结构中的任何值分配给该属性。 (在这种情况下为{ name: "", url:" }
)
如果user.profile.links
的值为null
,那么我想从预定义的结构中分配预定义的值/对象(在本例中为`
[
{
github: {
name: "",
url: "",
},
facebook: {
name: "",
url: "",
}
}
]
因此,只要结构不匹配,我都想用预定义结构中的预填充值替换它。我怎样才能做到这一点?预先感谢。
答案 0 :(得分:0)
您可以使用递归函数检查对象中是否存在预定义键。如果对象键未定义,为空或为null,则将预定义键值分配给对象:
function object_filter_recursive(obj, predefined) {
if ( typeof(predefined) == "object") {
Object.keys(predefined).forEach(function (k){
if (typeof obj[k] !== 'undefined' && obj[k] != '') {
if ( typeof(predefined[k]) == "object") {
return object_filter_recursive(obj[k], predefined[k]);
} else {
predefined[k] = obj[k];
}
}
})
}
return predefined;
}
var predefined = {
profile: {
name: "default name",
age: "", // if no default value, just leave it empty //
links: [
{
github: {
name: "default github",
url: "default github link",
},
facebook: {
name: "default facebook name",
url: "default facebook link",
}
}
]
},
posts: ""
}
var obj = {
profile: {
name: "john",
age: "40",
links: [
{
github: {
name: "",
url: "",
},
facebook: {
name: "",
url: "",
}
}
]
},
posts: [
{something1: "value1"},
{something2: "value2"}
]
}
obj = object_filter_recursive(obj, predefined);
console.log(obj);