'how to add a property to an object?
Given an object that has a "firstName" property and a "lastName" property, "addFullNameProperty" returns a "fullName" property whose value is a string with the first name and last name separated by a space.
var person = {
firstName: 'Jade',
lastName: 'Smith'
};
addFullNameProperty(person);
console.log(person.fullName); // --> 'Jade Smith'
my code :
function addFullNameProperty(obj) {
// your code here
obj[fullName] = obj.firstName + obj.lastName;
}
Solution 1:[1]
Just simple set:
obj.fullName instead of obj[fullName]
Or
obj['fullName']
Because fullName in your code is undefined variable. So JS alert error.
Solution 2:[2]
Either use obj.fullName
or obj['fullName']
But a more correct solution would be
function addFullNameProperty(obj) {
// your code here
Object.defineProperty(obj, 'fullName', {
get: function(){
return this.firstName + ' ' + this.lastName;
},
configurable:false
});
}
var person = {
firstName: 'Jade',
lastName: 'Smith'
};
addFullNameProperty(person);
console.log(person.fullName); // --> 'Jade Smith'
person.firstName = "Mike";
console.log(person.fullName); // --> 'Mike Smith'
This way your object will always return the correct fullName
.
Solution 3:[3]
If you want to add the space into the name, you will need to do string interpolation, like so:
`${obj.firstName} ${obj.lastName}`
and complement this with Gaby's answer about switching to dot notation, obj.fullName
Solution 4:[4]
Add new property to an existing object:
const person = {
firstName: 'Jade',
lastName: 'Smith'
};
person.fullName = `${person.firstName} ${person.lastName}`;
same as:
person['fullName'] = `${person.firstName} ${person.lastName}`;
or using method:
const person = {
firstName: 'Jade',
lastName: 'Smith',
fullName(){
return `${this.firstName} ${this.lastName}`;
}
};
person.fullName(); // Jade Smith
You can also use defineProperty
Solution 5:[5]
Try this
return obj.fullName = obj.firstName + " " + obj.lastName
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | taile |
Solution 2 | |
Solution 3 | |
Solution 4 | |
Solution 5 | Khalife |