X
X
XiNull2019-03-17 23:42:50
JavaScript
XiNull, 2019-03-17 23:42:50

How to push an object into an array?

Wrote such a piece of code, but something is not right.

let users = [];
...
users[socket] = {}; // Создаем новый объект
users[socket].id = results[0].id; // ID пользователя из бд
users[socket].nickname = results[0].nickname;
users.push(users[socket]); // Пушим, надо сохранить сокет как ключ, ибо по нему идёт перебор пользователей
...

How to properly push an object into an array?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Shvets, 2019-03-17
@XiNull

const users = [];
// ...
const server = net.createServer((socket) => {
    const newUser = {};
    newUser.socket = socket;
    newUser.id = results[0].id; // ID пользователя из бд -- не знаю уж где вы его возьмете
    newUser.nickname = results[0].nickname;
    users.push(newUser);
    c.on('data', function(data) {
});

And for some reason, you first declare an array, then you write down the ID in its properties. There will be no error, but it will no longer be an array.
Moreover, you specify a reference to an object as the property name, this is not WeakMap.

L
Leo, 2019-03-18
@DLeo13

An array is not an object. An object can be cast into an array, not vice versa.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question