简体   繁体   中英

how to create javascript object dynamically inside a function

I want to create a javascript object dynamically each time when I call "dataObject" function, so I wanted to do something like that :

let dataObject = {};

function appendDiv() {
    e = this.event.target;

    //this id changes each time when the function is called
    var current_id = e.id;

    // here I had to initialized it because if I didn't, it would appear an error "TypeError: dataObject[(intermediate value)] is undefined"
    dataObject[`${current_id}`] = {};

    $('#creates').submit(function (event) {
        var i, j;

        for (i = 0; i < nbr_group.value; i++) {
            inputlist = [];

            for (j = 0; j < 3; j++) {
                formChild = document.querySelectorAll('.period-select')[j].value;
                inputlist[j] = formChild;
            }

            dataObject[`${current_id}`][`${i}`] = {
                firstvalue: inputlist[0], 
                secondvalue: inputlist[1], 
                thirdvalue: inputlist[2]    
            }
        }
    });    
}

so the problem is when the function is called for the first time the subobjects will be created successfully but the second call for the function will be create them empty, for example:

// the first call:
dataObject = {
    '1': {
         '1': { '1': 'some values' }, 
         '2': { '1': 'another value' }
    }
};

//the second call or third or... :
dataObject = {
    '1': {
        '1': { '1': 'some values' }, 
        '2': { '1': 'another value' }
    },
    '2': {}
};        

If you would like to copy an object, don't use dataObject[`${current_id}`][`${i}`] = {firstvalue: inputlist[0], secondvalue: inputlist[1], thirdvalue: inputlist[2]}; , use this: let objectCopy = Object.assign({}, dataObject); where dataObject is your object you would like to duplicate.

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