(context)我从一堆元素中获取信息,我将这些元素收集到一个JSON对象中,然后传递给MVC3控制器,然后将其反序列化为一个对象。
有'商品'和'商品设置'。目前,我在平面JSON对象中都有项目和项目设置。理想情况下,我希望将项目设置嵌套在每个项目下。我的代码目前看起来像这样:
var editeditems=[];
...
$("#SaveChanges").click(function() {
//this works and retrieves all of the item IDs
$(".portlet").each(function() {
var itemname = $(this).data("itemname");
editeditems.push(
{
"itemname": itemname
});
itemname = $(this).data("itemname");
$(".settingInput").each(function() {
editeditems.push(
{
"settingkey":$(this).attr("name"),
"settingvalue":$(this).attr("value")
});
});
});
在$(“。settingInput”)下。每个函数都是添加设置的地方。我尝试过像'editedItems.settings.push ..'这样的语法,但它返回时出现语法错误。
非常感谢任何帮助!
答案 0 :(得分:13)
var editeditems = [];
...
$('#SaveChanges').click(function() {
$('.portlet').each(function() {
var settings = [];
$('.settingInput').each(function() {
settings.push({
settingkey: $(this).attr('name'),
settingvalue: $(this).attr('value')
});
});
editeditems.push({
itemname: $(this).data('itemname'),
settings: settings
});
});
...
});
将生成样本输出:
var editeditems =
[
{
"itemname": "item1",
"settings": [
{
"settingkey": "key1",
"settingvalue": "value1"
},
{
"settingkey": "key2",
"settingvalue": "value2"
}
]
},
{
"itemname": "item2",
"settings": [
{
"settingkey": "key1",
"settingvalue": "value3"
},
{
"settingkey": "key2",
"settingvalue": "value4"
}
]
}
];
答案 1 :(得分:3)
var ei = {'settings': [3]};
ei.settings.push(4);
console.log(ei);
// This will output an object with property settings and value an array with values (3 and 4)
答案 2 :(得分:1)
只需要创建像
这样的平面数据数组json[{"itemname": "item1","settingkey": "key1","settingvalue": "value1"},
{"itemname": "item2","settingkey": "key2","settingvalue": "value2"},];
不仅仅是这样的过程
var keys = Object.keys(dataMap);
var json = [];
for (var key in keys) {
var innerJson = {};
innerJson["name"] = keys[key];
var innerMap = dataMap[keys[key]];
if (innerMap instanceof Array) {
innerJson["size"] = innerMap[0];
} else if (innerMap instanceof Object) {
var child = processHirarchiachalData(innerMap);
innerJson["children"] = child;
}
json.push(innerJson);
}