[英]How to Create javascript json multidimensional tree from flat data
Hello guys I have a problem creating JSON tree from input form. 大家好,我在从输入表单创建JSON树时遇到问题。 Imagine you have one section of fields and then dynamically more sections are added.
假设您有一个字段部分,然后动态地添加了更多部分。 To be more precise, I am talking about switch properties.
更确切地说,我在谈论开关属性。 I just dont know how to add key as new array and then put there more properties with values.
我只是不知道如何将键添加为新数组,然后在其中放置更多具有值的属性。 Here is the code I am fighting with.
这是我正在使用的代码。
//FIRST section with just basic info about switch //第一部分仅提供有关开关的基本信息
function generateNewSwitchInDB() {
var portInfo = [];
$('#myModal').find('#inputs').find('input').each(function(){
var switchProperty = $(this)[0].id;
portInfo[switchProperty] = $(this)[0].value;
});
//SECOND section dynamically loop through new created sections and grab input id and input value // SECOND节动态循环遍历新创建的节并获取输入ID和输入值
portInfo.push({'portSlots' : 'portSlot'});
$('#myModal').find('.ports').each(function(){
portInfo[0]['portSlots'][$(this)[0].id] = $(this)[0].id;
$(this).find('input').each(function(){
var placeHolder = $(this)[0].placeholder;
portInfo[0]['portSlots']['0'][placeHolder] = $(this)[0].value;
});
});
console.log(portInfo);
}
What i want to achieve should look like this, but I cant figure out how to push there new key and to that key add properties. 我想要实现的目标应该看起来像这样,但是我无法弄清楚如何将新键推入该键并为该键添加属性。
{
'SwitchBasicInfo':{
'location':'Munich',
'vendor':'Cisco',
'hostname':'Switch123',
},
'Slots':{
'slot1':{
'numberOfEthernetPorts':'20',
'numberOfSerialPorts':'50',
'numberOfConsolePorts':'1',
},
'slot2':{
'numberOfEthernetPorts':'50',
'numberOfSerialPorts':'2',
'numberOfConsolePorts':'1',
},
'slot3':{
'numberOfEthernetPorts':'100',
'numberOfSerialPorts':'20',
'numberOfConsolePorts':'1',
},
}
}
Ok, I figured that out, every new level must begin with an array. 好的,我发现,每个新级别都必须以数组开头。
First section with basic data 第一部分基本数据
var newSwitchData = new Object();
newSwitchData = {'switchBasicInfo': {}};
newSwitchData.switchBasicInfo['switchProperty'] = $(this)[0].value;
Dynamic sections within foreach loop foreach循环中的动态部分
newSwitchData.portSlots = {};
newSwitchData.portSlots['slotId'] = {};
newSwitchData.portSlots['slotId']['placeHolder'] = $(this)[0].value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.