次の構造の JSON オブジェクトを作成したい... JSON オブジェクトにコメントを付けるべきではないことはわかっていますが、この例では目的の構造を説明したいだけです。
selObj = {
category: selectedCategory, // 1 category only
catOptions:{
optionValue:discountValue, // we can 1 or have many of paired keys in this sub object
optionValue:discountValue,
optionValue:discountValue
},
tariff:{
tariffValue:discountValue, // we can 1 or have many of paired keys in this sub object
tariffValue:discountValue
},
tarOptions:{
tarOption:discountValue // we can 1 or have many of paired keys in this sub object
}
};
これで、スクリプトの開始時に宣言した空のオブジェクトに値を設定する関数ができました…</p>
$(document).ready(function() {
var selObj = {};
populateMyEmptyObject(selObj)
});
populateMyEmptyObject(emptyObject){
emptyObject.category = "Category"
// in my original function I have loops that produce strings with the following structure {"value1":"10","value2":"20","value3":"30","value4":"40"}, for this example I’ll call them loopReturn1, loopReturn2, loopReturn3, loopReturn4
// loops have happened and vars are produced... I've removed my loops as they're working just fine, I've omitted that code for simplicity
emptyObject.catOptions = loopReturn1;
emptyObject.tariff = loopReturn2;
emptyObject.tarOptions = loopReturn3;
}
これで、空白の問題などで常にエラーが発生します。を使用するように言われましたがJSON.stringify
、まだ問題が発生しています。ループを忘れて、生成された文字列を取得してオブジェクトに追加する方法を教えてください。文字列を取得して、selObj という元のオブジェクトに変換/解析するためのベスト プラクティスを教えてください。また、関数で emptyObject を返して selObj を更新する必要がありますか (のようにreturn emptyObject;
)
次のように、元の空のオブジェクトを変更して、目的の構造をより適切に表す必要があります。
var selObj = {
"category": "selectedCategory",
"catOptions":{
},
"tariff":{
},
"tarOptions":{
}
};
アドバイスをいただければ幸いです。私が独学の開発者であることは明らかであり、私の知識にはいくつかの悪い習慣や穴があります。