繁体   English   中英

javascript嵌套object和arrays添加新元素问题

[英]javascript nested object and arrays adding new element problem

这是我的代码

let users2 = [
    {
        _id: 'ab12ex',
        username: 'Alex',
        email: 'alex@alex.com',
        password: '123123',
        createdAt:'08/01/2020 9:00 AM',
        isLoggedIn: false
    },
    {
        _id: 'fg12cy',
        username: 'Asab',
        email: 'asab@asab.com',
        password: '123456',
        createdAt:'08/01/2020 9:30 AM',
        isLoggedIn: true
    },
    {
        _id: 'zwf8md',
        username: 'Brook',
        email: 'brook@brook.com',
        password: '123111',
        createdAt:'08/01/2020 9:45 AM',
        isLoggedIn: true
    },
    {
        _id: 'eefamr',
        username: 'Martha',
        email: 'martha@martha.com',
        password: '123222',
        createdAt:'08/01/2020 9:50 AM',
        isLoggedIn: false
    },
    {
        _id: 'ghderc',
        username: 'Thomas',
        email: 'thomas@thomas.com',
        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','ali@mail.com','123',false)
signUp('kerem','kerem@protonmail.com','456',false)
signUp('johndoe','jd@jd.com','789',true)

当我首先获得新用户数据时,新用户数据与 rest 非常相似,但是当添加第二个(或更多)时,它错过了一个数组,它只是将数组变成 object

这是我的意思的例子,当我再添加一个用户然后前一个变得正常时

这里有什么问题

您似乎过于复杂地将 object 推送到数组

您要做的就是推users2用户2

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
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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