[英]javascript to build category tree from flat json array (data structure )
[英]How to Create javascript json multidimensional tree from flat data
大家好,我在從輸入表單創建JSON樹時遇到問題。 假設您有一個字段部分,然后動態地添加了更多部分。 更確切地說,我在談論開關屬性。 我只是不知道如何將鍵添加為新數組,然后在其中放置更多具有值的屬性。 這是我正在使用的代碼。
//第一部分僅提供有關開關的基本信息
function generateNewSwitchInDB() {
var portInfo = [];
$('#myModal').find('#inputs').find('input').each(function(){
var switchProperty = $(this)[0].id;
portInfo[switchProperty] = $(this)[0].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);
}
我想要實現的目標應該看起來像這樣,但是我無法弄清楚如何將新鍵推入該鍵並為該鍵添加屬性。
{
'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',
},
}
}
好的,我發現,每個新級別都必須以數組開頭。
第一部分基本數據
var newSwitchData = new Object();
newSwitchData = {'switchBasicInfo': {}};
newSwitchData.switchBasicInfo['switchProperty'] = $(this)[0].value;
foreach循環中的動態部分
newSwitchData.portSlots = {};
newSwitchData.portSlots['slotId'] = {};
newSwitchData.portSlots['slotId']['placeHolder'] = $(this)[0].value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.