How can I add firstName and lastName to fullName? - javascript

person = { firstName: 'Joseph', lastName: 'Magnolia', ageInYears: 34 }
function addFullName(personObj) {
person = { fullName: firstName + lastName, ageInYears: 34, }
}
It tells me undefined, and I have tried different things.

your code doesn't really make any sense, but did you mean something like this:
var person = { firstName: 'Joseph', lastName: 'Magnolia', ageInYears: 34 };
addFullName(person);
console.log(person);
function addFullName(personObj) {
personObj.fullName = personObj.firstName + ' ' + personObj.lastName;
}

Related

I've object {name: 'John', 'surname': 'Johnson', 'age': '20'}

Please tell me, I need to write a function that writes the corresponding values
into the variables name, surname and age.
How can this be implemented?
let user = {
name: 'John',
surname: 'Johnson',
age: '20',
};
let{name, surname, age} = user;
document.write(name + ' ' + surname + ' ' + age);
Ummm
function writeUser(user){
document.write(user.name + " " + user.surname + " " +user.age)
}
?
Let's see if this is something in the lines of what you're looking for:
const user = {
name: 'John',
surname: 'Johnson',
age: '20',
};
function updateUser(user) {
user.name = "New name";
user.surname = "New surname";
user.age = "New age";
}
updateUser(user);
const { name, surname, age } = user;
document.write(name + ' ' + surname + ' ' + age);
By adding an other parameter to this function you might make it more useful, like this:
function updateUser(user, overrides) {
Object.assign(user, overrides);
}
updateUser(user, { age: '30', name: 'New name' });
This would change the age and name but leave the surname, but it modifies the input user which isn't really a good pattern, better to return a new object instead:
function updateUser(user, overrides) {
return Object.assign({}, user, overrides); // First assign user to the empty object, then assign the overrides to that new object
}

Javascript Can't catch an error inside map function

let's say I have a usersList like this:
var usersList = [
{ firstName : 'Adam', lastName: 'Yousif', age: 23 },
{ firstName : 'Mohamed', lastName: 'Ali' },
{ firstName : 'Mona', lastName: 'Ahmed', age: 19 },
];
Now I want to call map function on usersList and return a modified list like so :
var returnList = usersList.map((_user) => {
var _age;
try {
_age = _user.age;
} catch (error) {
console.log('I caught error here : ', error); // <-- not printed
_age = 'FAILSAFE-VAULE'; // <-- not set
}
var obj = {
firstName: _user.firstName,
lastName: _user.lastName,
age: _age
}
return obj;
});
I have a try-catch block inside the map function, the purpose if it is to replace the undefined property "age" of the second user with a 'FAILSAFE-VALUE'. but it doesn't work as should.
console.log(returnList);
// prints
// [
// { firstName: 'Adam', lastName: 'Yousif', age: 23 },
// { firstName: 'Mohamed', lastName: 'Ali', age: undefined }, <-- not what I want
// { firstName: 'Mona', lastName: 'Ahmed', age: 19 }
// ]
How to catch an error inside javascript map function?
Thank you
You don't need to do try catch for that:
usersList.map((_user) => {
return {
firstName: _user.firstName,
lastName: _user.lastName,
age: _user.age || 'FAILSAFE-VAULE'
};
});
That's because nothing is thrown (the age is just undefined). If you want information about this "error" during the map-operation, the first part of the snippet may be an idea. If you really want to use try - catch, use the second part (it throws 'manually' when _user.age is undefined). The latter demonstrates (by the way) that try - catch does work within a map-operation.
const usersList = [{
firstName: 'Adam',
lastName: 'Yousif',
age: 23
},
{
firstName: 'Mohamed',
lastName: 'Ali'
},
{
firstName: 'Mona',
lastName: 'Ahmed',
age: 19
},
];
const getFailSafe = user => {
if (!user.age) {
console.log(`Note: user.age not available for ${user.firstName} ${user.lastName}`);
return `FAILSAFE-VAULE`;
}
return user.age;
};
// 1. use a warning if .age not present
const returnList = usersList
.map((_user) => ({
firstName: _user.firstName,
lastName: _user.lastName,
age: getFailSafe(_user)
})
);
// 2. throw an Error if .age not present
const returnListWithError = usersList
.map((_user) => {
let retVal = {
firstName: _user.firstName,
lastName: _user.lastName,
}
try {
retVal.age = _user.age ||
(() => {
throw new Error(`ERROR: user.age not available for ${
_user.firstName} ${_user.lastName} (will continue with 'FAILSAFE-VAULE')`);
})();
} catch (err) {
console.log(`${err.message}`);
retVal.age = `FAILSAFE-VAULE`;
}
return retVal;
});
console.log(returnList.find(v => isNaN(v.age)));
console.log(returnListWithError.find(v => isNaN(v.age)));
.as-console-wrapper { top: 0; max-height: 100% !important; }
try...catch block would not work there as after accessing a value which does not exist you just receive an undefined
just do it next way:
var returnList = usersList.map((_user) => {
return {
firstName: _user.firstName,
lastName: _user.lastName,
age: _user.age ? _user.age : 'FAILSAFE-VAULE'
}
});

This in function inside object Javascript

what is the wrong in this code , function fullAdress
i don't know what is the wrong in my code,
help my to fix it
var person = {
firstName: 'Ammar',
lastName: 'Gais',
age:21,
adress:{
street:'king road',
city:'atabra',
state:'River Nile'
fullAdress: function(){
return this.street+" "+this.city+" "+this.state;
}
},
fullName: function() {
return this.firstName+" "+this.lastName;
}
}
You are missing a comma after 'River Nile'. It is always recommended to look at the browser console for such errors. Even the object has properties or methods, everything should be separated by comma:
var person = {
firstName: 'Ammar',
lastName: 'Gais',
age: 21,
adress: {
street: 'king road',
city: 'atabra',
state: 'River Nile',
fullAdress: function() {
return this.street + " " + this.city + " " + this.state;
}
},
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
console.log(person.adress.fullAdress());
console.log(person.fullName());

Want to achieve functionality by using Javascripts map,reduce,foreach,filter methods

Please help me to write better code.
Suppose I have a JavaScript array like below:
var students = [
{ firstname: "stud1", lastname: "stud2", marks: "60" },
{ firstname: "stud3", lastname: "stud4", marks: "30" },
{ firstname: "stud5", lastname: "stud6", marks: "70" },
{ firstname: "stud7", lastname: "stud8", marks: "55" },
{ firstname: "stud9", lastname: "stud10", marks: "20" },
];
On page I want to show data in two parts, 1)Students who got marks >= 40 2)Students who got marks < 40
By using for loop I done this functionality easily as below.
var data = "";var data1 = "";
for (var i = 0; i < students.length; i++ )
{
if(students.marks >= 40){
data += = students.firstname + " " + students.lastname; //actual data in html div tag
....
}else{
data1 += = students.firstname + " " + students.lastname;
}
}
I want to achieve same functionality by using JavaScript methods like map, reduce, foreach, filter etc. (want to improve my JavaScript knowledge)
Don't know exactly which method is useful for such functionality.
Used map method and tried to display data, but there is a trailing , at the end of each object/array.
Can anyone please help/guide me to write proper code?
Here is solution using filter and forEach methods, using callback functions.
See references here :
filter method
var students = [
{ firstname: "stud1", lastname: "stud2", marks: "60" },
{ firstname: "stud3", lastname: "stud4", marks: "30" },
{ firstname: "stud5", lastname: "stud6", marks: "70" },
{ firstname: "stud7", lastname: "stud8", marks: "55" },
{ firstname: "stud9", lastname: "stud10", marks: "20" },
];
students.filter(function(item){
return item.marks>=40;
}).forEach(function(item){
div=document.getElementById('persons');
div.innerHTML+=item.firstname+' '+item.lastname+'<br>';
});
<div id="persons"></div>
You could use a single loop and add the information with predicate as index. Later join the elements for getting a sting for each element.
var students = [{ firstname: "stud1", lastname: "stud2", marks: "60" }, { firstname: "stud3", lastname: "stud4", marks: "30" }, { firstname: "stud5", lastname: "stud6", marks: "70" }, { firstname: "stud7", lastname: "stud8", marks: "55" }, { firstname: "stud9", lastname: "stud10", marks: "20" }],
predicate = function (o) { return o.marks >= 40; },
result = [[], []];
students.forEach(function (a) {
result[+predicate(a)].push(a.firstname + ' ' + a.lastname);
});
result = result.map(function (a) { return a.join(', '); });
console.log(result);

I created two different objects in one object. On printing them, only the last modified object is getting displayed. How to create?

var friends=new Object();
friends.bill=new Object();
friends.steve=new Object();
var friends={
bill:{
firstName: "Bill",
lastName: "gates",
number:'040404040',
address: ['bcd','sdad']
}
};
var friends={
steve:{
firstName: "Steve",
lastName: "Jobs",
number:'131313131',
address:['abc','sdsdsd']
}
};
console.log(friends);
the output of this program is all about the object "steve". If I log "friends.steve" it logs as "undefined". I want the output to be two diffrent objects in the object friend.
You are overriding the previously create object.
Rather you should try
var friends=new Object();
friends.bill=new Object();
friends.steve=new Object();
friends.bill={
firstName: "Bill",
lastName: "gates",
number:'040404040',
address: ['bcd','sdad']
};
friends.steve={
firstName: "Steve",
lastName: "Jobs",
number:'131313131',
address:['abc','sdsdsd']
};
console.log(friends);
To store multiple values in a variable you can use the Array.
var bill = {
firstName: "Bill",
lastName: "gates",
number:'040404040',
address: ['bcd','sdad']
}
var steve = {
firstName: "Steve",
lastName: "Jobs",
number:'131313131',
address:['abc','sdsdsd']
}
var friends = [bill, steve];
console.log(friends);
Also, in your code, you are defining the variable friends, which overwrite the variable defined with the same name. Additionally, you can define the class for friend and can create 2 objects from the class.
function Friend(firstname, lastname, number, address)
{
this.firstname = firstname;
this.lastname = lastname;
this.number = number;
this.address = address;
}
var bill = new Friend("Bill", "gates", "address", 040404040 ,['bcd','sdad']);
var steve = new Friend("Steve", "Jobs", "address", 131313131, ['abc','sdsdsd']);
var friends = [bill, steve];
console.log(friends);
In your code you define friends variable and override again in next few lines
'var friends={
bill:{'
This will override the first object and new instance will taking place instead.
Try this code and this will solve your problem
var friends = new Object();
friends.bill = {
firstName: "Bill",
lastName: "gates",
number:'040404040',
address: ['bcd','sdad']
};
friends.steve ={
firstName: "Steve",
lastName: "Jobs",
number:'131313131',
address:['abc','sdsdsd']
};
console.log(friends);

Categories

Resources