Search code examples
javascriptarraysjsonjavascript-objects

Create Objects inside an Object at Runtime(Dynamically) in Javascript


I am actually just building a form with vanilla JavaScript and I need a little help regarding how can we create something like this at runtime,

const users = {
   user1 : { name : "xyz", password : "1234", email : "[email protected]" },
   user2 : { name : "abc", password : "1111", email : "[email protected]" }
};

I want this because am using local storage to set values at run time but it only sets user1 values and not multiple users so please need a code which would help. Also it would be helpful to check whether below code is valid or not:

function submitData(inputArray) {
    inputArray.forEach(input => {
        users.push(input.value);
        localStorage.setItem(`${input.id}`, JSON.stringify(users))
    });
}    

Solution

  • Array.prototype.push only works off of arrays. If you had an array of objects you can make this work a little bit better, but you would lost the ability to look up a user, rather than having to iterate through the array to find it.

    What you could do if you really wanted to go through this route is find the last users number and create that as the property for the next object.

    something like this.

    const newUserNumber = Object.keys(users).length + 1
    const user = 'user' + newUserNumber
    users[user] = input.value
    

    Hope this helps!