让我们看一下下面的例子:
var ref = {
"fullName": {
"rules": {
"type": "string",
"minLength": 4,
"maxLength": 64
},
"description": "Full name of a user."
}
};
var user = {
"fullName": {
"rules": {
"required": true,
"maxLength": 128
},
"message": "You have submitted a wrong full name."
}
};
现在我想要的是:
- 合并对象和属性。
- 如果已经设置了第二个对象的属性,则保留它们(maxLength)
以下是我期望的结果:
var res = {
"fullName": {
"rules": {
"required": true,
"maxLength": 128
"type": "string",
"minLength": 4
},
"description": "Full name of a user.",
"message": "You have submitted a wrong full name."
}
};
我试过的:
function mergeNestedObjects(firstObject, secondObject) {
var finalObject = {};
for (var propertyKey in firstObject) {
var propertyValue = firstObject[propertyKey];
if (typeof(propertyValue) === "object") {
finalObject[propertyKey] = mergeNestedObjects(firstObject[propertyKey], secondObject[propertyKey]);
} else if (secondObject[propertyKey] === undefined) {
finalObject[propertyKey] = firstObject[propertyKey];
} else {
finalObject[propertyKey] = secondObject[propertyKey];
}
}
return finalObject;
}
上面的函数合并但不知何故不嵌套属性。
UPDATE & ANSWER让它工作了,我忘了遍历第二个对象,多么愚蠢。感谢@AnthonyGrist
function mergeProperties(propertyKey, firstObject, secondObject) {
var propertyValue = firstObject[propertyKey];
if (typeof(propertyValue) === "object") {
return mergeNestedObjects(firstObject[propertyKey], secondObject[propertyKey]);
} else if (secondObject === undefined || secondObject[propertyKey] === undefined) {
return firstObject[propertyKey];
}
return secondObject[propertyKey];
}
function mergeNestedObjects(firstObject, secondObject) {
var finalObject = {};
// Merge first object and its properties.
for (var propertyKey in firstObject) {
finalObject[propertyKey] = mergeProperties(propertyKey, firstObject, secondObject);
}
// Merge second object and its properties.
for (var propertyKey in secondObject) {
finalObject[propertyKey] = mergeProperties(propertyKey, secondObject, firstObject);
}
return finalObject;
}