简体   繁体   中英

How to Create javascript json multidimensional tree from flat data

Hello guys I have a problem creating JSON tree from input form. 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

    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

newSwitchData.portSlots = {};
newSwitchData.portSlots['slotId'] = {};
newSwitchData.portSlots['slotId']['placeHolder'] = $(this)[0].value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM