我想创建一个具有以下结构的 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":{
}
};
任何建议都将不胜感激,我认为很明显我是一名自学成才的开发人员,而且我有一些坏习惯和知识漏洞!