My question is somewhat simple, but IDK if I haven't made the search with the right keywords, but my problem is:
When defining an object in JS/TS, how can I use one value from the obj into another key, something like:
const person = {
firstName: 'Régis',
middleName: 'Faria',
fullName: `${firstName + middleName}` // Here is where IDK how to do it. I've tried with 'this.' but no success
}
Hope someone can help me out. Thanks in advance!!
Construct the object with firstName and middleName, then add the fullName:
const person = {
firstName: 'Régis',
middleName: 'Faria',
}
person.fullName = `${person.firstName} ${person.middleName}`;
To use this keyword, you must have an instance of an object, to do so, you can create a Person class and initialize a person.
class Person {
constructor({ firstName, middleName }) {
this.firstName = firstName
this.middleName = middleName
}
get fullName() {
return `${this.firstName} ${this.middleName}`
}
}
const person = new Person({
firstName: 'Régis',
middleName: 'Faria',
})
console.log(person.fullName)
Otherwise, you must set firstName and middleName first:
const firstName = 'Régis'
const middleName = 'Faria'
const person = {
firstName,
middleName,
fullName: `${firstName} ${middleName}`
}
console.log(person.fullName);
I personally prefer to use TypeScript:
// create a Person type
type Person {
firstName: string
lastName: string
fullName: string
}
// then it's ok to have variable
const firstName = 'Régis'
const middleName = 'Faria'
// then your person
const person: Person = {
firstName,
middleName,
fullName: `${firstName} ${middleName}`
}
console.log(person.fullName)