Search code examples
javascriptjsondommultidimensional-arraynodelist

Push a returned object into an array of objects


I'm trying to save the output of function setData (an object) to an array (state=[]), but can't figure out how. Here's the code:

const sbmt = document.getElementById("myForm");
const elName = document.getElementById("iname");
const elGender = document.getElementById("igender");
const elAge = document.getElementById("iage");
const elForm = document.getElementById("myForm");

const setData = (event) => {
    event.preventDefault();

    let nodeList = document.forms[0].elements;
    let flatNodeList = [...nodeList].map(x => x.value).filter(x => x !== "Submit");

    let objData = {
        userName: flatNodeList[0],
        userGender: flatNodeList[1],
        userAge: flatNodeList[2]
    };

    console.log(objData);

    return objData;
};

let state =[];

const resetForm = () => elForm.reset();

sbmt.addEventListener("submit", setData);
sbmt.addEventListener("submit", resetForm);

Solution

  • You basically just need to push the data into your state array. Returning the object will have no affect.

    let state =[];
    
    const setData = (event) => {
        event.preventDefault();
    
        let nodeList = document.forms[0].elements;
        let flatNodeList = [...nodeList].map(x => x.value).filter(x => x !== "Submit");
    
        let objData = {
            userName: flatNodeList[0],
            userGender: flatNodeList[1],
            userAge: flatNodeList[2]
        };
    
        console.log(objData);
    
        state.push(objData);
    };