は、以下の例を見てみましょう、ネストされたプロパティを持つオブジェクトをマージ: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."
}
};
は今、私が欲しいのはこれです:
- マージは&プロパティオブジェクト。
- 彼らが既に設定されている場合(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;
}
を
上記の関数はマージしますが、何らかの形でプロパティをネストしません。 & ANSWERはそれが働いてしまった
UPDATEどのようにダム、私は、第二の目的によってすぎitterate忘れてしまいました。おかげで
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:あなたのコードを試したところ、プロパティは正しくネストされていました。唯一の問題は、Anthony氏が指摘しているように、いくつかのプロパティが欠落していることです。 – RonaldBarzell
@AnthonyGristは働いていた、私の愚かな笑い。しかし、私はこれを持っています:http://pastebin.com/Zma8kLY6これはどんな短くてもかまいません。複写されたコードをたくさん使っているようです。 – onlineracoon