讓我們來看看下面的例子:的Javascript合併對象與嵌套屬性
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."
}
};
現在我想是這樣的:
- 合併對象&性能。
- 保持第二對象的屬性,如果他們已經被設置(最大長度)
下面是結果,我想到:
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 &回答讓它工作,我忘記了太多通過第二個對象,通過多少啞劇。由於@AnthonyGrist
function mergeProperties(propertyKey, firstObject, secondObject) {
var propertyValue = firstObject[propertyKey];
if (typeof(propertyValue) === "object") {
return mergeNestedObjects(firstObject[propertyKey], secondObject[propertyKey]);
} else if (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;
}
你永遠只能迭代firstObject'的'鍵,所以你得到的對象只是以往任何時候都具有相同的密鑰傳遞的第一個對象。你還需要遍歷鍵'secondObject',並添加那些丟失的。 –
@onlineracoon:我試過你的代碼,並且屬性正確嵌套。正如安東尼指出的那樣,唯一的問題是某些財產不見了。 – RonaldBarzell
@AnthonyGrist工作,我多麼愚蠢。現在,但我得到了這個:http://pastebin.com/Zma8kLY6可以做得更短,它看起來像我做了很多重複的代碼 – onlineracoon