How to make user add object with required field? - javascript

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:
users = [newUser, ...users];
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.

You should also check for new user's first and last name as they are required.
i.e: && newUser.first_name && newUser.last_name.
You can simply
if(newUser && typeOf newUser === "object" && newUser.first_name && newUser.last_name){
//add to []
}else {
//show message code
}

You already have an if block to check if it's a valid user, why not use it to check if first_name is set?
As for adding an object at the beginning of an array, you could use the expand operator for that. ([newElement, ...array])
class UserList {
constructor(users) {
this.users = users;
}
add(newUser) {
if (typeof newUser === 'object' && newUser.first_name) {
users = [{id: users.length, ...newUser}, ...users];
console.log(`Hello everyone i am ${newUser.first_name}`);
} else {
console.log('Please add object where first_name field is required!');
}
}
}
EDIT:
As Linschlager was quick to point out, you can even make it a one-liner by creating a new object from id: users.length and expanding the newUser object.

Related

Storing a variable in an array (that functions as a value in an object) JavaScript

I have a simple function that checks if the username already exists in the array of objects, in case it does, it should save new time in an array in format { username: username, time: [firsttime, secondtime, etc] }. The code itself is rough, but the problem is that if the username doesn't exist (and the array is not empty, so there are some other usernames saved already), the function saves the time two times, if I try the same username, I get one more object with double time.
let array = []
const userName = prompt("username")
const userTime = prompt("points")
if (array.length > 0) {
for (let i = 0; i < array.length; i++) {
if (array[i].username === userName) {
array[i].time.push(userTime)
} else {
const thisTime = {
username: userName,
time: [userTime]
}
array.push(thisTime)
}
}
} else {
const firstTime = {
username: userName,
time: [userTime]
}
array.push(firstTime)
console.log(array)
}
So on the first round i get [{username: "maria", time: Array(1)}]
On the second round with another username [{username: "maria", time: Array(1)}, {username: "ariana", time: Array(2) e.g. [14,14] (should be only 1 value)}]
The code was edited according to the rules, so actual username and time are added in course of the game.
You could do that with a more efficient and less error prone way:
// look for the index in the array
const pointIndex = this.points.findIndex(point => point.username === this.username);
if(pointIndex > -1){ // if found, push the time
this.points[pointIndex].time.push(this.globalTime);
}
else { // push a new point otherwise
const thisTime = {
username: this.username,
time: [this.globalTime]
}
this.points.push(thisTime)
}

Using if/else to define const in Javascript

I'm using const in a function to define a few variables as follows
const printBlock.format({
name : this.matchedData.clientName,
date : this.matchedData.jobDate,
destination : this.matchedData.address,
apartment : this.matchedData.address2,
stateZip : this.matchedData.zipcode
})
From then, I'm printing out all of these things in order that they're declared. However, some of the data doesn't have an apartment number so it'll show up as:
John Doe
6/6/2018
135 Testdemo Avenue
null
NY 11111
Is it possible to use an if function within declaring the consts in order to make it so that:
if (this.matchedData.address2 == null){
//Do nothing
} else {
apartment : this.matchedData.address2,
}
No, but you can use a ternary
var object = {
address: '1111',
apartment : this.matchedData.address2 ? "" : this.matchedData.address2
}
You could use Object.assign and check with property and if not null, take an object for assignment.
printBlock(Object.assign(
{
name: this.matchedData.clientName,
date: this.matchedData.jobDate,
destination: this.matchedData.address,
apartment: this.matchedData.address2,
stateZip: this.matchedData.zipcode
},
this.matchedData.address2 === null || { apartment: this.matchedData.address2 }
));
You can create your object first without the apartment entry and then add the apartment entry if it is not null...
const a = {
name : this.matchedData.clientName,
date : this.matchedData.jobDate,
destination : this.matchedData.address,
stateZip : this.matchedData.zipcode
};
if (this.matchedData.address2 !== null){
a.apartment : this.matchedData.address2;
}
const printBlock({...}) will throw an error because it isn't a valid way to initialize a constant. If printBlock is a function, why not handle null values in the body of printBlock?
function printBlock(obj) {
for (var prop in obj) {
if (obj[prop]) {
console.log(obj[prop]); // or do whatever you mean by 'print'
}
}
}

The JavaScript function returns else statement though the search value exists in the array

I am trying to search for a userName in the given Array below. The Search function returns true for second element when searching for second element in the array of objects, where as it returns false for first element when searching for first element. It should return true when we search for a existing value in the Array, but the function returns false for first element, true for second element.
I could not find out the mistake I am doing. Even tried using Array.prototype.find() function, but no luck.
//JSON User Information
var userProfiles = [
{
"personalInformation" : {
"userName" : "Chandu3245",
"firstName" : "Chandrasekar",
"secondName" : "Mittapalli",
"Gender" : "Male",
"email" : "chandxxxxx#gmail.com",
"phone" : ["740671xxx8", "8121xxxx74"]
}
},
{
"personalInformation" : {
"userName" : "KounBanega3245",
"firstName" : "KounBanega",
"secondName" : "Karodpati",
"Gender" : "Male",
"email" : "KounBanega3245#gmail.com",
"phone" : ["965781230", "8576123046"]
}
}
];
function findUserDataWithUserID (userData, userid){
var fullName = "";
//iterates through userData array
userData.forEach(function(user){
//checks for matching userid
if(user.personalInformation.userName === userid){
fullName=user.personalInformation.firstName+" "+user.personalInformation.secondName;
}else{
fullName = "Userid Not Found";
}
});
return fullName;
}
console.log(findUserDataWithUserID(userProfiles, "Chandu3245"));
You can also use the Array.prototype.some() method for this.
The some method is similar to the every method, but works until the return of the function is true. For more information visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
function checkProfile (profiles,userid) {
var message = "Userid not found"
profiles.some(function(user) {
if(user.personalInformation.userName === userid) {
message = user.personalInformation.firstName+" "+user.personalInformation.secondName;
}
})
console.log(message);
};
checkProfile(userProfiles,"KounBanega3245");
That is because it is running the if case in the first iteration of the forEach, then in the second iteration, it processes the second item in the array, causing the else clause to run.
A more holistic approach would be to use filter/map/reduce:
userProfiles
// Only keep the one that we want
.filter(function(user) {
return user.personalInformation.userName === userid;
})
// extract the user's name
.map(function(user) {
return user.personalInformation.firstName + " " + user.personalInformation.secondName;
})
// Get the first (and only) item out of the array
.pop();
This does not solve for any error checking (like if the user is not in the original array).

AngularJS - grabbing specific data from an JSON array

Here is a picture of what the API is returning:
I am trying to create variables that grab the "Current Approver" and "Status" from this array. And if the "Current Approver" matches the username stored in local storage and the "Status" is "REJECTED" then I want to run a line of jquery.
Here is what I have:
$http.get( API + '/car' ).
success(function(data) {
$scope.myCars = data;
console.log(data);
var originator = $scope.myCars["My CARs"]["Current Approver"],
status = $scope.myCars["My CARs"].Status,
user = localStorage.getItem('user') || null
// Check if logged in user is originator and CAR is "REJECTED"
if (originator === user && status === 'REJECTED') {
$('#termCar').css('display', 'block');
}
});
Here is the HTML:
<div ng-repeat="car in myCars['My CARs']" class="myCar">
<div class="carId">{{ car['Display Name'] }}</div>
<div class="title">{{ car['Project Title'] }}</div>
<div id="termCar" class="termCar"><a ui-sref="taskDetails">Terminate</a></div>
</div>
I know that it has something to do with these lines (obviously):
originator = $scope.myCars["My CARs"]["Current Approver"],
status = $scope.myCars["My CARs"].Status
I just cant figure out how to pull specific data out of an array i guess.
I need to be able to loop through the array of objects and find the ones that meet that if statement and then if one of those does then run the jQuery line.
Thanks for any help.
Try:
originator = $scope.myCars["My CARs"][0]["Current Approver"];
status = $scope.myCars["My CARs"][0].Status
You're simply not referencing which index in the array you wish to grab the values from.
You're right, the issue is this:
$scope.myCars["My CARs"]["Current Approver"]
For that to work, your data structure would have to look like this:
"My CARS": {
"Current Approver": "..."
}
My CARs is an array of objects, so you need to iterate over that array. You would typically do this with a basic forEach. Lodash makes this nice to do, but I'll use native js:
var user = localStorage.getItem('user');
$http.get('/car').success(function(data) {
var cars = data['My CARs'];
cars.forEach(function(car) {
if (car["Current Approver"] === user && car.Status === 'REJECTED') {
// do stuff
}
});
});
you need to filter the array My CARs to match the local user
$http.get(API + '/car').success(function(data) {
$scope.myCars = data;
console.log(data);
var user = localStorage.getItem('user') || null;
var originator = $scope.myCars["My CARs"].filter(function(d) {
return d["Current Approver"] === user && d["Status"] === 'REJECTED'
});
if (originator.length) {
$('#termCar').css('display', 'block');
}
});
Try this:
var cars = $scope.myCars["My CARs"];
for(int i = 0; i < cars.length; i++) {
var theCar = cars[i];
if(theCar["Current Approver"] === user && theCar["Status"] === "REJECTED") {
originator = theCar["Current Approver"];
status = theCar.Status;
break;
}
}
This will give you the status of the first car that matches whose Current Approver matches the user.

JavaScript / AngularJS modify property in array

I have the following AngularJS model:
$scope.Model = {
Users : [{
UserId: '',
FirstName: '',
LastName: ''
}],
Products :[{
ProductId: '',
Price: ''
}]
};
If I populate this array with N users, and one user has id=1, how can I update that specific user (with id=1) the property LastName?
So for example if I will get a new AngularJS model:
$scope.UserToUpdate ={
UserId: 1,
LastName: "Smith"
};
I want to loop through the $scope.Model array and update the user with id=1 but only the FirstName property.
P.S. I don't know at what position the target user object in the array it is so basically can be at $scope.Model.Users[0] or $scope.Model.Users[1] or $scope.Model.Users[10] or at $scope.Model.Users[N] ...
You can just loop through your list of users
for (var i = 0; i < $scope.Model.Users.length; i++) {
if($scope.Model.Users[i].UserId === $scope.UserToUpdate.UserId) {
$scope.Model.Users[i].LastName = $scope.UserToUpdate.LastName;
break;
}
}
EDIT: Actually harish's answer is on to something too. Here's another solution using $filter:
var matchedUsers = $filter('filter')($scope.Model.Users, { UserId: $scope.UserToUpdate.UserId });
if (matchedUsers.length > 0) {
matchedUsers[0].LastName = $scope.UserToUpdate.LastName;
}
And don't forget to add the $filter service as a parameter in your controller declaration for this second solution.
$scope.UserToUpdate =
$scope.Model.Users.filter(function(user) { return user.FirstName == "test"; })[0];
BTW: you can add a check if the user exists..
you can use $filter
var user = $filter('filter')($scope.Model.Users, 'UserId == 1');
you are read more about $filter('filter') here
Try this! working demo http://plnkr.co/edit/scyV79HqqA7nOG9h4ezH?p=preview . Please check the console log.
angular.forEach($scope.Model[0].Users, function(value1, key1) {
var i = 0;
angular.forEach(value1, function(value, key) {
if (key == 'UserId' && $scope.UserToUpdate.UserId == value) {
$scope.Model[0].Users[i].LastName = $scope.UserToUpdate.LastName;
}
i++;
});
});
The above code updating the Model object LastName property based on UserToUpdate object (id=1)

Categories