call() is not working with getter and setter in javascript - javascript

let Name = {
get fullname() {
return this.fname + this.last
}
}
function pension() {
return this.age > 60
}
let firstclass_employee = [{
fname: "sangeth",
last: "AV",
age: 21,
address: {
housename: "good house",
place: "goodplace",
city: "goodtwon",
postcode: 121212
},
hobbies: ["driving", "travelling", "sports"]
}, {
fname: "ramu",
last: "kv",
age: 29,
address: {
housename: "etho veedu",
place: "vayadi",
city: "kalur",
postcode: 11111
},
hobbies: ["travelling", "sports"]
}]
console.log(" objects::\t", Name, "\n", firstclass_employee)
//calling a out side function for an object(out side function may be inside an object oe not)
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
console.log("Pension status of of first emlpoyee::", pension.call(firstclass_employee[0]))
console.log("Fullname of 2nd employee::", Name.fullname.call(firstclass_employee[1]))
console.log("Pension status of of 2nd emlpoyee::", pension.call(firstclass_employee[1]))
AND getting error--->
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
^
TypeError: Name.fullname.call is not a function

remove get - which is not a valid here
let Name = {
fullname() {
return this.fname + this.last
}
}

If you want regular function remove the get and it will work fine. Sorry, I was mistakenly said you have errors in the console.log() part.
let Name = {
fullname() {
return this.fname + this.last
}
}
function pension() {
return this.age > 60
}
let firstclass_employee = [{
fname: "sangeth",
last: "AV",
age: 21,
address: {
housename: "good house",
place: "goodplace",
city: "goodtwon",
postcode: 121212
},
hobbies: ["driving", "travelling", "sports"]
}, {
fname: "ramu",
last: "kv",
age: 29,
address: {
housename: "etho veedu",
place: "vayadi",
city: "kalur",
postcode: 11111
},
hobbies: ["travelling", "sports"]
}]
console.log(" objects::\t", Name, "\n", firstclass_employee)
//calling a out side function for an object(out side function may be inside an object oe not)
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
console.log("Pension status of of first emlpoyee::", pension.call(firstclass_employee[0]))
console.log("Fullname of 2nd employee::", Name.fullname.call(firstclass_employee[1]))
console.log("Pension status of of 2nd emlpoyee::", pension.call(firstclass_employee[1]))

As far as why the call() is invalid is that Name.fullname is not exposed as a function. It is exposed the same way as a field would be, e.g.
const Name = {
fullname: 'Bob'
};
With that structure, you wouldn't expect to be able to call Name.fullname.call, right? But for the purposes of getting the value, that's what the prior code exposed to the outside world (the difference with the field being that you can set the value, whereas with a getter and no setter, the property is read only).
The get essentially tells the JavaScript engine that, whenever someone asks for the value of fullname, give them the value of the fname and last properties concatenated together.
Thus, when you ask for Name.fullname.call(firstclass_employee[0]) it first finds Name. Then it asks for the value of fullname. It gets back NaN, because this is the Name object and it doesn't have fname or last properties, and it tries to coerce the first undefined (from this.fname) to a Number for the addition operator, and gets NaN. Then it tries to get the call function on NaN, and there is no such thing, so it throws an error.
It appears as though you want to be able to get a full name from any object that has fname and last properties. I would suggest using static method for that rather than an instance property getter.
Similarly, a static method would work for determining employees who get a pension.
Personally, I would just create a class or series of classes that I could compose together to bring this functionality together, rather than trying to use call, but that's me.
const Name = {
fullName(obj) {
return `${obj.fname} ${obj.last}`;
}
};
const Pay = {
getsPension(obj) {
return obj.age > 60;
}
}
let firstclass_employee = [{
fname: "sangeth",
last: "AV",
age: 21,
address: {
housename: "good house",
place: "goodplace",
city: "goodtwon",
postcode: 121212
},
hobbies: ["driving", "travelling", "sports"]
}, {
fname: "ramu",
last: "kv",
age: 29,
address: {
housename: "etho veedu",
place: "vayadi",
city: "kalur",
postcode: 11111
},
hobbies: ["travelling", "sports"]
}]
console.log('should be sangeth AV: ', Name.fullName(firstclass_employee[0]));
console.log('should be false: ', Pay.getsPension(firstclass_employee[0]));

Related

How to remove extra unknown properties from object in javascript

I was just wondering is it possible to remove extra unknown properties from object.
The exact problem which I am facing is that I know what fields I need in object, but I don't know what extra is coming and I need to remove those extras.
One option which comes in my mind is using hasOwnProperty function since we know what all properties we need.
Ex : Suppose we are getting below object :
{
name: "Harry",
age: 16,
gender: "Male",
Address: {
prop1: "Hello",
City: "LA"
}
}
Now, we know that we need name, age, address and city in address beforehand but we are getting prop1 also as extra here and we don't know that it is exactly. It could be anything. We need to remove this prop1 from this object. This is just an example.
I think we need to use some recursive approach because the extra property could be at any place in the object.
Note: We have a list of properties which we need in advance.
I defined a schema form of json (modify it as you want) and then I made a function that receives the json required to delete unwanted elements from it.
const needAttribute = {
name: "Harry",
age: 16,
gender: "Male",
Address: {
City: "LA"
}
}
var json =
{
name: "Harry",
age: 16,
gender: "Male",
Address: {
prop1: "Hello",
City: "LA"
}
}
function getNeedAttributeFromJson(Myjson){
for(var element in Myjson){
if(needAttribute.hasOwnProperty(element)){
if (typeof Myjson[element] === "object") {
for(var subElement in Myjson[element]){
if(!needAttribute[element].hasOwnProperty(subElement)){
delete Myjson[element][subElement];
}
}
}else{
continue;
}
}else{
delete Myjson[element];
}
}
return Myjson;
}
console.log(getNeedAttributeFromJson(json));
You can use lodash library.
REFERENCE URL - https://lodash.com/docs/4.17.15#omit
const object = {
name: "Harry",
age: 16,
gender: "Male",
Address: {
prop1: "Hello",
City: "LA"
}
object = _.omit(object.Address, 'prop1');
console.log(object);

this keyword within a function of an object not returning expected value

I am new to coding and learning about the this keyword, I'm expecting the function in the stephen object to perform the calculation given to it (2022-1995) and for that result to show, but it seems like the this keyword is not defined and I do not know why after trying to fix it for hours.
const stephen = {
firstName: 'Stephen',
lastName: 'McColgan',
job: 'Admin',
friends: ['Chris', 'Simon', 'Thea', 'N/A'],
hasDriversLicense: true,
age: 1995,
calcAge: function() {
this.birthYear = 2022 - this.age;
return this.birthYear;
}
};
console.log(stephen.age);
console.log(stephen.birthYear);
You are not the calling the calcAge() function before displaying the age. So It is returning undefined cause this.birthYear will be initialize when you will call the function. So first you should call calcAge() function and the display the age.
In your case birthYear and age got swapped. Here is working code:
const stephen = {
firstName: 'Stephen',
lastName: 'McColgan',
job: 'Admin',
friends: ['Chris', 'Simon', 'Thea', 'N/A'],
hasDriversLicense: true,
birthYear: 1995,
calcAge: function() {
this.age = 2022 - this.birthYear;
return this.age;
}
};
stephen.calcAge();
console.log(stephen.age);

How can i get both object length together from chain of object

Say I create a Object as follows
const myObj1 = {
firstName: "Shaheb",
lastName: "Ali",
professions:"Web Developer"
}
And create another object with the above object to add as a prototype object
const myObj2 = Object.create(myObj1, {
age:{
value:33
},
edu:{
value: "MBA"
}
});
now I want to count length of both object together, how can i?
I understand you want to get count of all keys in your object(s). As there is no length property available for objects (only for arrays), you should use Object.keys(), which returns an array with all keys:
const myObj1 = {
firstName: "Shaheb",
lastName: "Ali",
professions:"Web Developer"
}
Object.keys(myObj1).length; // would return '3'
I believe that instead of Object.create(), you actually want to use Object.assign(), which will assign all keys from myObj1 to myObj2:
const myObj1 = {
firstName: "Shaheb",
lastName: "Ali",
professions:"Web Developer"
}
const myObj2 = {
age:{
value:33
},
edu:{
value: "MBA"
}
}
Object.assign(myObj2, myObj1);
document.write(Object.keys(myObj2).length + '<br>'); // return '5'
document.write(Object.keys(myObj1).length); // return '3'
If I understand the OP goal:
const myObj1 = {
firstName: "Shaheb",
lastName: "Ali",
professions:"Web Developer"
}
const myObj2 = {
age:{
value:33
},
edu:{
value: "MBA"
}
};
const result = {...myObj1, ...myObj2};
console.log(result);
const length = Object.keys(result).length;
console.log(length);
{ firstName: 'Shaheb',
lastName: 'Ali',
professions: 'Web Developer',
age: { value: 33 },
edu: { value: 'MBA' }
}
5
const obj = Object.create(myObj1, myObj2);
create prototyping object looks like below
{age: 33, edu: "MBA"}
age: 33
edu: "MBA"
proto:
firstName: "Shaheb"
lastName: "Ali"
professions: "Web Developer"
proto: Object
but assigning a object is like a combining 2object into one. is this not possible to get the length from plan object and prototyping object together?
but your ans was awesome, help me a lot to make it better understand. if it is not possible then i will follow your suggestions.

Advanced Destructuring of objects in ES6

I have the following object:
personObj = {
_id : '123',
first_name: 'John',
last_name: 'Doe',
}
I would like to destructure it to the following variables:
id, <-- _id
name: {
first, <-- first_name
last <-- last_name
}
(I want first_name and last_name to reside inside a 'name' object)
I've tried the following syntax:
const {
id: _id,
name: {
first: first_name,
last: last_name
}
} = personObj
However this causes an error.
What am I doing wrong?
Update
Chapter 10. Destructuring of book "Exploring ES 6" provides many advanced examples of how to use destructuring and explains how it works internally.
Destructuring can extract values directly into the properties of an object. The properties are not required to exist but all destination objects must already exist when the destructuring assignment happens.
Armed with this knowledge, the code that answers the question is:
let personObj = {
_id: '123',
first_name: 'John',
last_name: 'Doe',
}
// Create the objects that receive the values on destructuring
let c = { name: {} }
// Do the magic
({ _id: c.id, first_name: c.name.first, last_name: c.name.last } = personObj)
console.log(c)
// {id: "123", name: {first: "John", last: "Doe"}}
The parentheses around the assignment expression that uses destructuring are required, without them the engine reports a syntax error at the first :.
The original answer follows. It doesn't completely answer the question but I leave it here for reference. It shows how to use the rest properties (...) in destructuring expressions and it was accepted by the OP, as incomplete as it is.
The original answer
Destructuring with properties renaming works the other way around: the original name is placed before the colon, the new name is after it.
let personObj = {
_id: '123',
first_name: 'John',
last_name: 'Doe',
}
// Destructure personObj using different names for the properties
const {
_id: id,
first_name: first,
last_name: last
} = personObj
console.log('id: ' + id);
console.log('first: ' + first);
console.log('last: ' + last);
// Output
// id: 123
// first: John
// last: Doe
You can then assemble the pieces (id, first, last) into a new object:
let c = {
id,
name: {
first,
last
}
}
console.log(c);
// Output
// { id: '123', name: { first: 'John', last: 'Doe' } }
Update
The most similar result to what you describe in the question can be achieved by:
let { _id: id, ...name } = personObj
console.log(id)
console.log(name)
// Output
// 123
// { first_name: 'John', last_name: 'Doe' }
But this way the properties of name use the same names they have in personObj. Even more, it doesn't work any more if you add to personObj properties after last_name that you don't want to copy in name.

How to call for object keys in javascript (codecademy)

I'm following an online course in Javascript from Codecademy but i'm stuck in an assignment.
I'm trying to list the firstName key from my "friends list".
I have to do this with a "for in" statement in a function.
The firstName key is within the object "Steve", which in in an object "Friends".
This is the code that i have at the moment:
var friends = {
steve: {
firstName: 'Steve',
lastName: 'Jobs',
number: '1',
address: ['Fregataan','65','8546','RG','Amsterdam','The Netherlands'],
},
bill: {
firstName: 'Bill',
lastName: 'Gates',
number: '2',
address: ['Fregataan','665','8546','RG','Amsterdam','The Netherlands'],
},
};
function list(friends){
for (var firstName in friends){
console.log(friends.keys(firstName))
}
}
list(friends.keys);
This is the assignment I get from the course:
1. Create a function list that takes a single parameter.
2. In the body of the function, write a for/in loop.
3. In the loop, use console.log to print out the key. (For example, if you only have bill and steve as entries, list should just print out "bill" and "steve".)
The object "friends" was already written in a previous assignment. The function has to be written in this assignment. Can someone please find my mistake and tell me what i did wrong?
Greetings,
Luuk
I think it might be a tricky question. You are trying to print the firstName key which (if done correctly) will print out "Steve" and "Bill", but the assignment, as you described it, is to print out the key (i.e. "steve" and "bill"). So if that's the case, you should just print out the key:
function list(friends){
for (var key in friends){
console.log(key);
}
}
Hope this helps.
You should play around with it a bit more.
No need to use 'keys'.
var friends = {
steve: {
firstName: 'Steve',
lastName: 'Jobs',
number: '1',
address: ['Fregataan','65','8546','RG','Amsterdam','The Netherlands'],
},
bill: {
firstName: 'Bill',
lastName: 'Gates',
number: '2',
address: ['Fregataan','665','8546','RG','Amsterdam','The Netherlands'],
},
};
function list(friends){
console.log(friends);
for (var friend in friends){
console.log(friend);
var f = friends[friend];
console.log(f.firstName);
}
}
list(friends);

Categories