Home > Software engineering >  javascript nested object and arrays adding new element problem
javascript nested object and arrays adding new element problem

Time:02-19

here is my code piece

let users2 = [
    {
        _id: 'ab12ex',
        username: 'Alex',
        email: '[email protected]',
        password: '123123',
        createdAt:'08/01/2020 9:00 AM',
        isLoggedIn: false
    },
    {
        _id: 'fg12cy',
        username: 'Asab',
        email: '[email protected]',
        password: '123456',
        createdAt:'08/01/2020 9:30 AM',
        isLoggedIn: true
    },
    {
        _id: 'zwf8md',
        username: 'Brook',
        email: '[email protected]',
        password: '123111',
        createdAt:'08/01/2020 9:45 AM',
        isLoggedIn: true
    },
    {
        _id: 'eefamr',
        username: 'Martha',
        email: '[email protected]',
        password: '123222',
        createdAt:'08/01/2020 9:50 AM',
        isLoggedIn: false
    },
    {
        _id: 'ghderc',
        username: 'Thomas',
        email: '[email protected]',
        password: '123333',
        createdAt:'08/01/2020 10:00 AM',
        isLoggedIn: false
    }
    ];

const date = new Date()
let exactTime = date.toLocaleString('en-KL', { hour: 'numeric', minute: 'numeric', hour12: true })

const signUp = (username,email,password,isLoggedIn) => {
    let obj = {
        _id: 'ddfcd',
        username: username,
        email: email,
        password: password,
        createdAt:`${date.getDate()}/${date.getMonth()}/${date.getFullYear()} ${exactTime}`,
        isLoggedIn: isLoggedIn
    }
    let arr = [`${users2.length}`, obj]
    let collection = Object.entries(users2)
    collection.push(arr)
    users2 = collection
}

signUp('ali','[email protected]','123',false)
signUp('kerem','[email protected]','456',false)
signUp('johndoe','[email protected]','789',true)

when i get new user data at first the new one is exacrly similar with the rest however when add second one (or more) it misses an array it just turns array into object

here is the example what i mean when i add one more user then the previous one gets normal

what's the problem here

CodePudding user response:

You seem to have overcomplicated pushing an object to an Array

All you want to do is push to users2

const signUp = (username,email,password,isLoggedIn) => {
    users2.push({
        _id: 'ddfcd',
        username: username,
        email: email,
        password: password,
        createdAt:`${date.getDate()}/${date.getMonth()}/${date.getFullYear()} ${exactTime}`,
        isLoggedIn: isLoggedIn
    });
}
  • Related