I have an array with 50 users. So then i've a method add:(should accept object of user (field firstName is required), add it to array of users, (user id for new user should be generated programmatically and be unique))
const users = [{
"id": 1,
"first_name": "Abner",
"last_name": "Glaisner",
"gender": "Male",
"language": "Tswana"
}, {
//...
}]
class UserList {
constructor(users) {
this.users = users;
}
add(newUser) {
if (typeof newUser === 'object' && typeof newUser !== null) {
users.push(newUser);
newUser.id = users.length;
console.log(`Hello everyone i am ${newUser.first_name}`);
} else {
console.log('Please add object where first_name field is required!');
}
}
}
So what i need is when user writes
UserList.add({
first_name: 'Jack',
last_name: 'Nollan',
//...
})
Make him to fill first_name
.
Is it possible to do ?
And also i use newUser.id = user.length to generate user's id, is it possible to push it at the begining of object not to the end of it ?
Answering your second question; You could achieve it by using the array spread operator you could do something like this:
Note that this overwrites the array every time you add something to it. Another approach would be to
Array.reverse
it where you use it.