1

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!!

2 Answers2

1

Construct the object with firstName and middleName, then add the fullName:

const person = {
  firstName: 'Régis',
  middleName: 'Faria',
}
person.fullName = `${person.firstName}  ${person.middleName}`;
Christian
  • 7,433
  • 4
  • 36
  • 61
1

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)
Dimitri Kopriwa
  • 13,139
  • 27
  • 98
  • 204
  • Thank you for the complete answer. I was hoping to accomplish this by the object declaration, but I guess It's not possible. – Régis Faria Aug 27 '21 at 19:34